目录 一、处理缺失数据 1. 检查缺失数据 2. 填充缺失数据 3. 删除缺失数据 二、数据聚合 一、处理缺失数据 在数据处理过程中,经常会遇到数据缺失的问题。Pandas为此提供了一些方法来
- 一、处理缺失数据
- 1. 检查缺失数据
- 2. 填充缺失数据
- 3. 删除缺失数据
- 二、数据聚合
在数据处理过程中,经常会遇到数据缺失的问题。Pandas为此提供了一些方法来处理缺失数据。
1. 检查缺失数据使用isnull()和notnull()函数,可以检查DataFrame对象中的每个元素是否为空。
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],
columns=['one', 'two', 'three'])
df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print(df['one'].isnull())
2. 填充缺失数据
Pandas提供了一个fillna()函数,可以使用常数值或前一个或后一个数据点来填充空值。
print(df.fillna(0)) # 使用0来填充空值 print(df.fillna(method='pad')) # 使用前一个数据点来填充空值3. 删除缺失数据
如果你想删除包含缺失值的行,可以使用dropna()函数。
print(df.dropna())二、数据聚合
数据聚合是数据处理的重要步骤,Pandas提供了一个强大的groupby功能,可以按照一个或多个列对数据进行分组,然后对每个分组应用一个函数。
import pandas as pd
df = pd.DataFrame({
'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.random.randn(8)
})
# 分组并对每个分组进行求和
print(df.groupby('A').sum())
# 按多个列进行分组形成层次索引,然后执行函数
print(df.groupby(['A', 'B']).mean())
Pandas的数据聚合功能非常强大,可以使用各种函数(如mean、sum、size、count、std、var等)进行聚合操作。
通过
