我有一个包含两列的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
第四行已成为空值。在这种情况下,我希望得到一个NaN值,因为两个合并列都是NaN。
0 apple-martini
1 apple-pie
2 strawberry-tart
3 dessert
4 None
dtype: object
fillna
后删除type
列?即避免另一个drop
语句。 - sjd