gpt4 book ai didi

python - Pandas 两列之和 - 正确处理纳米值

转载 作者:行者123 更新时间:2023-12-02 06:55:38 24 4
gpt4 key购买 nike

当对两个 pandas 列求和时,当两列之一是 float 时,我想忽略纳米值。但是,当 nan 出现在两列中时,我想将 nan 保留在输出中(而不是 0.0)。

初始数据框:

Surf1     Surf2
0 0
NaN 8
8 15
NaN NaN
16 14
15 7

所需输出:

Surf1     Surf2     Sum
0 0 0
NaN 8 8
8 15 23
NaN NaN NaN
16 14 30
15 7 22

尝试过的代码:-> 下面的代码忽略 nan 值,但是当取两个 nan 值之和时,它在输出中给出 0.0,在这种特殊情况下我想将其保留为 NaN,以将这些空值与实际为 0 的值分开求和后。

import pandas as pd
import numpy as np

data = pd.DataFrame({"Surf1": [10,np.nan,8,np.nan,16,15], "Surf2": [22,8,15,np.nan,14,7]})
print(data)

data.loc[:,'Sum'] = data.loc[:,['Surf1','Surf2']].sum(axis=1)
print(data)

最佳答案

来自documentation pandas.DataFrame.sum

By default, the sum of an empty or all-NA Series is 0.

>>> pd.Series([]).sum() # min_count=0 is the default 0.0

This can be controlled with the min_count parameter. For example, if you’d like the sum of an empty series to be NaN, pass min_count=1.

将代码更改为

data.loc[:,'Sum'] = data.loc[:,['Surf1','Surf2']].sum(axis=1, min_count=1)

输出

   Surf1  Surf2
0 10.0 22.0
1 NaN 8.0
2 8.0 15.0
3 NaN NaN
4 16.0 14.0
5 15.0 7.0
Surf1 Surf2 Sum
0 10.0 22.0 32.0
1 NaN 8.0 8.0
2 8.0 15.0 23.0
3 NaN NaN NaN
4 16.0 14.0 30.0
5 15.0 7.0 22.0

关于python - Pandas 两列之和 - 正确处理纳米值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61636049/

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