gpt4 book ai didi

python - Pandas 根据其他细胞的连续性填充细胞

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

我有一个 df 有很多丢失的数据,但基本上是相同的列(源自合并数据集)。例如,请考虑以下内容:

temp = pd.DataFrame({"fruit_1": ["apple", "pear", "don't want to tell", np.nan, np.nan, np.nan],
"fruit_2": [np.nan, np.nan, "don't want to tell", "apple", "don't want to tell", np.nan],
"fruit_3": ["apple", np.nan, "pear", "don't want to tell", np.nan, "pear"]})

我现在想把它们合并成一列;冲突应按如下方式解决:

  • np.nan 总是被其他信息覆盖
  • “不想说”只会覆盖 np.nan
  • 任何其他值仅覆盖 np.nan 和“不想告诉”(即保留第一个值)。

我已经尝试创建一个新列并使用apply(见下文)。

temp.insert(0, "fruit", np.nan)
temp['fruit'].apply(lambda row: row["fruit"] if np.isnan(row["fruit"]) and not np.isnan(row["fruit_1"]) else np.nan) # map col

然而,该代码产生了一个TypeError: 'float' object is not subscriptable

有人能告诉我 (1) 这是否是一般可行的方法 - 如果是这样,我的错误是什么? (2) 最有效的方法是什么?

非常感谢。

** 编辑 **预期的输出是

                fruit             
0 apple
1 pear
2 pear
3 apple
4 don't want to tell
5 pear

最佳答案

使用 ffill 和额外的 np.where

s=temp.mask(temp=="don't want to tell").bfill(1).iloc[:,0]
s=np.where((temp=="don't want to tell").any(1)&s.isnull(),"don't want to tell",s)
s
Out[17]:
array(['apple', 'pear', 'pear', 'apple', "don't want to tell", 'pear'],
dtype=object)
temp['New']=s
temp
Out[19]:
fruit_1 ... New
0 apple ... apple
1 pear ... pear
2 don't want to tell ... pear
3 NaN ... apple
4 NaN ... don't want to tell
5 NaN ... pear
[6 rows x 4 columns]

关于python - Pandas 根据其他细胞的连续性填充细胞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57959116/

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