【问题标题】:rename columns of second dataframe with column names of first dataframe based on a list基于列表用第一个数据框的列名重命名第二个数据框的列
【发布时间】:2022-09-22 23:03:57
【问题描述】:

我想用 df1 的列名重命名 df2 的列名并打印新的 df2 数据框。 我还想从新的 df2 中删除 \"df1_cols_to_rename_df2\" 中未列出的列

import pandas as pd
    
    
data1 = {\'first_column\':  [\'1\', \'2\', \'2\'],
            \'second_column\': [\'1\', \'2\', \'2\'],
           \'third column\':[\'1\', \'2\', \'2\'],
          \'fourth_column\':[\'1\', \'2\', \'2\'],
           \'fifth_column\':[\'1\', \'2\', \'2\'],
            }
    
data2 = {\'1st_column\':  [\'1\', \'2\', \'4\'],
            \'some_column\': [\'1\', \'2\', \'2\'],
            \'3rd_column\':[\'1\', \'2\', \'2\'],
            \'4th_column\':[\'7\', \'2\', \'2\'],
            \'5th_column\':[\'1\', \'4\', \'2\'],
            \'2nd_column\':[\'1\', \'5\', \'3\'],
            }
    
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)

df1_cols_to_rename_df2 = {\'first_column\':[\'1st_column\'], \'second_column\':[\'2nd_column\'], \'third column\':[\'3rd_column\'],\'fourth_column\':[\'4th_column\']]

所以这将是预期的输出

  • 您是如何在预期输出中选择第五列的?
  • 我的错误我刚刚编辑了它,正是我不希望新 df2 输出中的第五列

标签: python pandas list dataframe rename


【解决方案1】:

注意: df1_cols_to_rename_df2 没有第五列,但存在于预期中。原因尚不清楚。假设是 OP 中的错字。

# invert the key values in the dict df1_cols_to_rename_df2
d={ df1_cols_to_rename_df2[k][0]: k for k in df1_cols_to_rename_df2.keys()}

# choose the columns (values) in the dict and rename these
df2.loc[:, df2.columns.isin(d.keys())].rename(columns=d )
first_column    third column    fourth_column   second_column
0   1   1   7   1
1   2   2   2   5
2   4   2   2   3

【讨论】:

    【解决方案2】:

    我们可以使用rename 方法来更改列名,如下所示:

    df2 = df2.rename(columns={'1st_column': 'first_column', 
                              '2nd_column': 'second_column',
                              '3rd_column': 'third_column',
                              '4th_column': 'fourth_column',
                              '5th_column': 'fifth_column'})
    

    然后只保留所需的列:

    df2 = df2[list(set(df1) & set(df2))]
    

    输出 :

        first_column    second_column   third_column    fourth_column   fifth_column
    0   1               1               1               7               1
    1   2               5               2               2               4
    2   4               3               2               2               2
    

    【讨论】:

    • 嘿 tlentali,我想根据列表重命名列并将列表中不存在的列删除到 df 中
    • 嘿@yoopiyo,希望你一切都好!我更新了答案,只保留来自df_1 的列并检查了输出。它回答了你的问题吗?
    • 我纠正了列选择的错误:)!现在工作正常。
    • 我的问题可能不是很清楚,我想要 df1 的一些列并重命名 df2,所以我制作了一个列表“df1_cols_to_rename_df2”来选择我用来重命名 df2 的那些 df1 列
    猜你喜欢
    • 2021-11-15
    • 2021-11-01
    • 2018-03-09
    • 2021-01-11
    • 2021-08-14
    • 2023-03-12
    • 2022-07-05
    • 1970-01-01
    • 2019-10-02
    相关资源
    最近更新 更多