熊猫:用列表替换列中的非空行

时间:2020-06-24 13:11:20

标签: python pandas list replace

我有一个类似于以下(但更长)的数据框,其中某些行包含None值:

data = {'first Column':  ['she is', 'they are',NaN,'we are',NaN],
    'second Column ': ['my', 'her',NaN,'his',NaN],
    'third column': ['friend', 'brothers',NaN,'sisters',NaN]
    }

df = pd.DataFrame (data, columns = ['first Column','second Column','third column])

my_list = ['金','银','青铜']

如果不包含任何值,我想用列表替换“第三列”中的每一行,例如:

  desired output:
     first column   second column   third column
  0  she is          my             ['gold','silver','bronze']
  1  they are        her            ['gold','silver','bronze']
  2  NaN             NaN            NaN
  3  we are          his            ['gold','silver','bronze']
  4  NaN             NaN            NaN

我尝试了np.where,但是它没有选择所需的行

   np.where(df.loc[df['third column'] != 'NaN', [','.join(my_list)], df['third column']

1 个答案:

答案 0 :(得分:2)

df.loc[df['third column'].notna(),'third column']=[my_list]

结果:

  first Column second Column             third column
0       she is             my  [gold, silver, bronze]
1     they are            her  [gold, silver, bronze]
2          NaN            NaN                     NaN
3       we are            his  [gold, silver, bronze]
4          NaN            NaN                     NaN

PS:如果您将data指定为具有列名的字典,则在数据帧构造函数中不需要columns参数。