【问题标题】:Creating a new column in Pandas based on the values of two other columns [duplicate]根据其他两列的值在 Pandas 中创建一个新列[重复]
【发布时间】:2021-03-19 07:04:17
【问题描述】:

我想根据其他两列的值在 Pandas 数据集中创建一个新列。

+-----------+----------+
| Column_1  | Column_2 |
+-----------+----------+
| a         | c        |
+-----------+----------+
| b         | d        |
+-----------+----------+

现在,new_column 应该如下所示:

+-----------+----------+------------+
| Column_1  | Column_2 | new_column |
+-----------+----------+------------+
| a         | c        | a,c        |
+-----------+----------+------------+
| b         | d        | b,d        |
+-----------+----------+------------+

有什么帮助吗?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以在应用 concat 时创建一个辅助数据框 (df_new),以便将统一列与生成的 index 列一起取消透视。然后按新的index列分组后使用apply(lambda x: ','.join(x)),如

    import pandas as pd
    
    fields = {'Column_1': ['a','b'],
              'Column_2': ['c','d']
              }
    
    df=pd.DataFrame(fields)
    df_new = pd.concat([df[i] for i in df.columns]).reset_index()
    df['new_column']=df_new.groupby(['index'])[0].apply(lambda x: ','.join(x)).reset_index()[0]
    

    【讨论】:

    • 我认为不需要groupby
    【解决方案2】:

    我用过这个,效果很好:

    df['new_column'] = df['Column_1']+ ' , ' +df['Column_2']
    

    【讨论】:

    • 如果您有两个以上的列,例如 'Column_3': ['d','e'] 怎么办。我的意思是你也需要明确添加' , ' +df['Column_3']。例如。将为每一列产生编码。
    猜你喜欢
    • 1970-01-01
    • 2020-08-18
    • 2020-06-02
    • 1970-01-01
    • 2021-07-08
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多