pandas 将两列与空值组合在一起

编程入门 行业动态 更新时间:2024-10-10 10:24:33
本文介绍了 pandas 将两列与空值组合在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have a df with two columns and I want to combine both columns ignoring the NaN values. The catch is that sometimes both columns have NaN values in which case I want the new column to also have NaN. Here's the example:

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 并解决这个问题:

I tried to use fillna and solve this :

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

我得到:

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

第 4 行变成了空值.在这种情况下我想要的是 NaN 值,因为两个组合列都是 NaN.

The row 4 has become a blank value. What I wan't in this situation is a NaN value since both the combining columns are NaNs.

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

推荐答案

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

Use fillna on one column with the fill values being the other column:

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

结果输出:

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

更多推荐

pandas 将两列与空值组合在一起

本文发布于:2023-11-30 07:38:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649199.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   pandas   将两列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!