用str.cat() 或者用“+” 拼接,注意要将na替换,否则结果拼接结果也是na
df = pd.DataFrame([['a', 'b', 'c'], [pd.np.nan, "b", "c"]], columns=list('ABC'))
print(df)
A B C
0 a b c
1 NaN b c
df = df.fillna('') #将NA换成str,方便查NA
df['new'] = df['A'] + np.where(df['B'] != '', ' '+df['B'], '') + np.where(df['C'] != '', ' '+df['C'], '')
# np.where(condition, A, B) 满足条件输出A,否则输出B
# 若没有条件A,和B,则输出满足条件元素的下标
print(df)
A B C new
0 a b c a b c
1 b c b c
这篇博客介绍了如何使用Python的pandas库处理DataFrame中的缺失值(NA),通过fillna方法将其替换为空字符串,并展示了如何利用np.where和str.cat()函数结合列值进行条件拼接,创建新的字符串列。
913

被折叠的 条评论
为什么被折叠?



