gpt4 book ai didi

python - Pandas 将两列与空值结合起来

转载 作者:IT老高 更新时间:2023-10-28 21:08:04 25 4
gpt4 key购买 nike

我有一个包含两列的 df,我想合并两列而忽略 NaN 值。问题是有时两列都有 NaN 值,在这种情况下,我希望新列也有 NaN。示例如下:

df = pd.DataFrame({'foodstuff':['apple-martini', 'apple-pie', None, None, None], 'type':[None, None, 'strawberry-tart', 'dessert', None]})

df
Out[10]:
foodstuff type
0 apple-martini None
1 apple-pie None
2 None strawberry-tart
3 None dessert
4 None None

我尝试使用 fillna 来解决这个问题:

df['foodstuff'].fillna('') + df['type'].fillna('')

我得到了:

0      apple-martini
1 apple-pie
2 strawberry-tart
3 dessert
4
dtype: object

第 4 行已成为空白值。在这种情况下我想要的是一个 NaN 值,因为两个组合列都是 NaN。

0      apple-martini
1 apple-pie
2 strawberry-tart
3 dessert
4 None
dtype: object

最佳答案

使用 fillna在一列上,填充值为另一列:

df['foodstuff'].fillna(df['type'])

结果输出:

0      apple-martini
1 apple-pie
2 strawberry-tart
3 dessert
4 None

关于python - Pandas 将两列与空值结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41449555/

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