gpt4 book ai didi

python - Pandas 数据框列减法,处理 NaN

转载 作者:行者123 更新时间:2023-12-03 21:44:05 40 4
gpt4 key购买 nike

例如,我有一个数据框

df = pd.DataFrame([(np.nan, .32), (.01, np.nan), (np.nan, np.nan), (.21, .18)],
columns=['A', 'B'])
A B
0 NaN 0.32
1 0.01 NaN
2 NaN NaN
3 0.21 0.18
我想减去列 B来自 A
df['diff'] = df['A'] - df['B']

A B diff
0 NaN 0.32 NaN
1 0.01 NaN NaN
2 NaN NaN NaN
3 0.21 0.18 0.03
如果其中一列是 NaN,则差值返回 NaN .为了克服这个问题,我使用 fillna
df['diff'] = df['A'].fillna(0) - df['B'].fillna(0)

A B diff
0 NaN 0.32 -0.32
1 0.01 NaN 0.01
2 NaN NaN 0.00
3 0.21 0.18 0.03
这解决了 NaN进入 diff 列,但对于索引 2,结果是 0 ,而我想要差异为 NaN因为 A 列和 B 列是 NaN .
有没有办法明确告诉 Pandas 输出 NaN如果两列都是 NaN?

最佳答案

使用 Series.sub fill_value=0范围:

df['diff'] = df['A'].sub(df['B'], fill_value=0)
print (df)
A B diff
0 NaN 0.32 -0.32
1 0.01 NaN 0.01
2 NaN NaN NaN
3 0.21 0.18 0.03
如果需要将 NaN 替换为 0添加 Series.fillna :
df['diff'] = df['A'].sub(df['B'], fill_value=0).fillna(0)
print (df)
A B diff
0 NaN 0.32 -0.32
1 0.01 NaN 0.01
2 NaN NaN 0.00
3 0.21 0.18 0.03

关于python - Pandas 数据框列减法,处理 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65731024/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com