根据其他列将列添加到数据框

时间:2020-06-18 22:22:20

标签: python pandas dataframe copy nan

仅当'col_A'的内容为数字而不是NaN时,我才想将'col_B'的内容复制到新列中。我很欣赏这看似基本,但我对python还是很陌生。预先感谢

  col_A  col_B  col_C  col_D

0      NaN    2      a      b
1      2      4      b      d
2      NaN    1      c      a
3      4      2      d      b
4      5      3      e      c

1 个答案:

答案 0 :(得分:1)

您可以在此处使用numpy.where

df['new_col'] = np.where(~df['col_A'].isna(), df['col_B'], '')
print(df)

   col_A  col_B col_C col_D new_col
0    NaN      2     a     b
1    2.0      4     b     d       4
2    NaN      1     c     a
3    4.0      2     d     b       2
4    5.0      3     e     c       3