【问题标题】:Pandas - Creating new column if not exist [duplicate]Pandas - 如果不存在则创建新列[重复]
【发布时间】:2022-01-06 05:39:34
【问题描述】:

我有一个以下格式的数据框

col_1, col_2, col_3
1, 2, 3
2, 3, 4
2, 3, 5

我正在尝试检查 Dataframe 是否有一组列,如果没有,我想将它们创建为 Dataframe 中的新列

cols_to_check = ['col_1', 'col_2', 'col_6', 'col_9']

为此,我想先创建 col_6col_9,因为它们在 Dataframe 中不存在。

最终输出:

col_1, col_2, col_3, col_6, col_9
1, 2, 3, 0, 0
2, 3, 4, 0, 0
2, 3, 5, 0, 0

【问题讨论】:

    标签: pandas dataframe


    【解决方案1】:

    使用reindex

    cols_to_check = ['col_1','col_2', 'col_3', 'col_6', 'col_9']
    df.reindex(columns=cols_to_check).fillna(0)
    

    以防万一,您不确定是否所有 df 列都包含在新列表中,利用集合来检查并使用 set union 添加

    cols_to_check = ['col_1','col_2', 'col_3', 'col_6', 'col_9']
    new_list =list(set(df.columns).union(cols_to_check))
    new_df=df.reindex(columns=sorted(new_list)).fillna(0)
    print(new_df)
    
    
    
       col_1  col_2  col_3  col_6  col_9
    0      1      2      3    0.0    0.0
    1      2      3      4    0.0    0.0
    2      2      3      5    0.0    0.0
    

    【讨论】:

      猜你喜欢
      • 2021-07-08
      • 2016-01-22
      • 2013-11-16
      • 1970-01-01
      • 2019-10-17
      • 2012-12-13
      • 2013-03-26
      • 2016-01-13
      • 1970-01-01
      相关资源
      最近更新 更多