gpt4 book ai didi

python - 涉及 nan 的数据框操作

转载 作者:太空宇宙 更新时间:2023-11-04 00:47:41 25 4
gpt4 key购买 nike

我想从 Dataframe 中的所有行中减去具有 nan 值的行。为此,我正在使用

dataframe.sub(row, axis= 1)

这会忽略 nan 值,即如果两行中的任何一个值为 nan,则结果为 nan。我希望如果两个值中的任何一个不是 nan,则减法应该将 nan 值设为 0。如果两者都不是 nan,则结果应该是差值。如果两者都是 nan,则结果应该是 nan。比如下面两行的减法应该是这样的,

[1, 2, nan, nan, 5] - [nan, 5, 1, nan, 2] = [1 , -3, -1, nan, 3]

我该怎么做?

最佳答案

I want that if either of the values is not nan, the subtraction should proceed taking the nan value to be 0. If both are not nan, the result should be the difference.

使用 fillnanan 值设置为 0,然后应用掩码将结果重置为 nan,其中两个输入值为

import pandas as pd
import numpy as np
# sample data
nan = np.nan
df = pd.DataFrame({ 'a': [1, 2, nan, nan, 5],
'b': [nan, 5, 1, nan, 2] })
# get all rows with both values nan
nan_mask = df.a.isnull() & df.b.isnull()
# calculate with all nans set to 0
result = df.a.fillna(0) - df.b.fillna(0)
# set rows with both nans to nan
result[nan_mask] = nan
print list(result)
=> [1.0, -3.0, -1.0, nan, 3.0]

更新

如果您正在寻找更简洁的解决方案,结果证明 df.sub(other, fill_value=0.0) 实现了同样的事情:

df = pd.DataFrame({ 'a': [1, 2, nan, nan, 5],
'b': [nan, 5, 1, nan, 2]})
result = df.a.sub(df.b, fill_value=0.0)
=> [1.0, -3.0, -1.0, nan, 3.0]

From the docs :

fill_value : None or float value, default None (NaN) Fill missing (NaN) values with this value. If both Series are missing, the result will be missing

关于python - 涉及 nan 的数据框操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38680797/

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