仅将文本附加到非空值pandas Dataframe

as *_* if 3 python pandas

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

|  id | qty  | item |
+-----+------+------+
| 001 |  700 | CB04 |
| 002 |  500 |      |
| 003 | 1500 | AB01 |
Run Code Online (Sandbox Code Playgroud)

我想将文本追加boxdf['item']item不为null的位置,因此New df将如下所示:

|  id | qty  |   item   |
+-----+------+----------+
| 001 |  700 | CB04 box |
| 002 |  500 |          |
| 003 | 1500 | AB01 box |
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 7

对于我没有检查NaN的工作解决方案:

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

检查解决方案NaN:

使用notnaloc

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
Run Code Online (Sandbox Code Playgroud)

或者numpy.where:

df['item'] = np.where(df['item'].notna(), df['item'] + ' box',  df['item'])
#df['item'] = np.where(df['item'].notnull(), df['item'] + ' box',  df['item'])
Run Code Online (Sandbox Code Playgroud)