仅将文本附加到非空值

2024-10-16 17:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个df,看起来像这样:

|  id | qty  | item |
+-----+------+------+
| 001 |  700 | CB04 |
| 002 |  500 |      |
| 003 | 1500 | AB01 |

我想将文本box附加到df['item']中,其中项不为null,因此新的df将如下所示:

|  id | qty  |   item   |
+-----+------+----------+
| 001 |  700 | CB04 box |
| 002 |  500 |          |
| 003 | 1500 | AB01 box |

Tags: 文本boxiddfitemnullqtyab01
1条回答
网友
1楼 · 发布于 2024-10-16 17:22:25

对于我来说,没有检查的工作解决方案NaNs:

df['item'] += ' box'
print (df)
   id   qty      item
0   1   700  CB04 box
1   2   500       NaN
2   3  1500  AB01 box

检查NaN的解决方案:

^{}loc一起使用

df.loc[df['item'].notna(), 'item'] += ' box'
#for oldier pandas versions
#df.loc[df['item'].notnull(), 'item'] += ' box'
print (df)
   id   qty      item
0   1   700  CB04 box
1   2   500       NaN
2   3  1500  AB01 box

^{}

df['item'] = np.where(df['item'].notna(), df['item'] + ' box',  df['item'])
#df['item'] = np.where(df['item'].notnull(), df['item'] + ' box',  df['item'])

相关问题 更多 >