猿问

如果存在另一列中的值,如何从单元格中清除值?

我有 df 看起来像这样:


col1    col2 

NaN     text

text    text

NaN     text

NaN     text

我想在清除值col2,如果NaN如果存在col1。


新 df 应如下所示:


col1    col2 

NaN     

text    text

NaN     

NaN     


手掌心
浏览 157回答 3
3回答

缥缈止盈

您正在寻找masking 操作:df['col2'] = df['col2'].mask(df.col1.isna(), '')# df['col2'] = np.where(df.col1.isna(), '', df['col2'])df   col1  col20   NaN      1  text  text2   NaN      3   NaN      如果您希望在第二列中使用 NaN 而不是空白,请将第二个参数省略为mask。

海绵宝宝撒

使用dropna+reindexdf.dropna('col1').reindex(df.index) # fixing by cold :-)   col1  col20   NaN   NaN1  text  text2   NaN   NaN3   NaN   NaN
随时随地看视频慕课网APP

相关分类

Python
我要回答