【问题标题】:pandas: replace non-empty rows in a column with a listpandas:用列表替换列中的非空行
【发布时间】:2020-10-14 18:16:05
【问题描述】:

我有一个如下数据框(但更长),其中一些行包含 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= ['gold','silver','bronze']

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

  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']

【问题讨论】:

    标签: python pandas list replace


    【解决方案1】:
    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 指定为带有列名的 dict,则不需要在数据框构造函数中使用 columns 参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 2018-01-31
      • 2021-02-28
      相关资源
      最近更新 更多