在处理Pandas的函数应用上,遇到一个坑,当我们在调用 axis 属性时,一不小心很容易入坑,在处理缺失数据 dropna 和通过 apply 将函数应用到每个数据上,axis表示的不同。
1、 dropna 在使用 axis 时,
默认 axis=0 表示按行,只要行有NaN就去除此行
axis=1 表示按列,只要列有NaN就去除此列
下面是源码的解释:
axis : {0 or 'index', 1 or 'columns'}, or tuple/list thereof
Pass tuple or list to drop on multiple axes
2、 apply 在使用 axis 时,
默认 axis=0 表示按列计算,这里和上面的不同
axis=1 表示按行计算
下面是源码的解释:
axis : {0 or 'index', 1 or 'columns'}, default 0
* 0 or 'index': apply function to each column
* 1 or 'columns': apply function to each row
例:
处理缺失数据
示例代码:
df_data = pd.DataFrame([np.random.randn(3), [1., 2., np.nan],
[np.nan, 4., np.nan], [1., 2., 3.]])
print(df_data.head())
运行结果:
0 1 2
0 -0.281885 -0.786572 0.487126
1 1.000000 2.000000 NaN
2 NaN 4.000000 NaN
3 1.000000 2.000000 3.000000
1. 判断是否存在缺失值:isnull()
示例代码:
# isnull
print(df_data.isnull())
运行结果:
0 1 2
0 False False False
1 False False True
2 True False True
3 False False False
2. 丢弃缺失数据:dropna()
根据axis轴方向,丢弃包含NaN的行或列。 示例代码:
# dropna
print(df_data.dropna())
# 默认 axis=0 表示按行,只要行有NaN就去除此行
# 程序源代码解释>>>>>
# axis : {0 or 'index', 1 or 'columns'}, or tuple/list thereof
# Pass tuple or list to drop on multiple axes
print(df_data.dropna(axis=1))# axis=1 表示按列,只要列有NaN就去除此行
运行结果:
0 1 2
0 -0.281885 -0.786572 0.487126
3 1.000000 2.000000 3.000000
1
0 -0.786572
1 2.000000
2 4.000000
3 2.000000
apply 和 applymap
1. 可直接使用NumPy的函数
示例代码:
# Numpy ufunc 函数
df = pd.DataFrame(np.random.randn(5,4) - 1)
print(df)
print(np.abs(df))
运行结果:
0 1 2 3
0 -1.714216 -1.612752 -1.646193 -1.003224
1 -1.586357 -0.441958 -2.359834 -1.254230
2 -1.923455 -0.529722 -0.182811 -1.030291
3 -1.231890 0.365055 -1.908999 0.362850
4 -0.810931 -1.476705 -2.959405 -0.625998
0 1 2 3
0 1.714216 1.612752 1.646193 1.003224
1 1.586357 0.441958 2.359834 1.254230
2 1.923455 0.529722 0.182811 1.030291
3 1.231890 0.365055 1.908999 0.362850
4 0.810931 1.476705 2.959405 0.625998
2. 通过apply将函数应用到列或行上
示例代码:
# 使用apply应用行或列数据
#f = lambda x : x.max()
print(df.apply(lambda x : x.max()))
注意指定轴的方向,默认axis=0,方向是列
# 程序源代码解释>>>>>
# axis : {0 or 'index', 1 or 'columns'}, default 0
# * 0 or 'index': apply function to each column
# * 1 or 'columns': apply function to each row
示例代码:
# 指定轴方向,axis=1,方向是行
print(df.apply(lambda x : x.max(), axis=1))
运行结果:
0 -0.810931
1 0.365055
2 -0.182811
3 0.362850
dtype: float64
0 -1.003224
1 -0.441958
2 -0.182811
3 0.365055
4 -0.625998
dtype: float64