【问题标题】:renaming of columns in pandas using other data frame使用其他数据框重命名熊猫中的列
【发布时间】:2017-07-03 13:36:13
【问题描述】:

假设我有 4 列的数据框:

df = pd.DataFrame({'one': [1., 2., 3., 4.],
    'two': [4., 3., 2., 1.],
    'three': [4., 3., 2., 1.],
    'four': [4., 3., 2., 1.]})

并假设有另一个数据框(2 列): 第一列由数据框 df('one','two','three','four') 的列的名称组成,下一列由名称组成,我想将 @ 的列名更改为987654323@数据框。

如何在 pandas 中用一/两行代码做到这一点?

【问题讨论】:

    标签: pandas


    【解决方案1】:

    您需要 renamedictSeries

    print (df1)
           a  b
    0    one  c
    1    two  d
    2  three  e
    3   four  f
    
    d = df1.set_index('a')['b'].to_dict()
    #by Series
    #d = df1.set_index('a')['b']
    print (d)
    {'four': 'f', 'two': 'd', 'three': 'e', 'one': 'c'}
    
    df = pd.DataFrame({'one': [1., 2., 3., 4.],
        'two': [4., 3., 2., 1.],
        'three': [4., 3., 2., 1.],
        'four': [4., 3., 2., 1.]})
    print (df)
    
    df = df.rename(columns=d)
    print (df)
         f    c    e    d
    0  4.0  1.0  4.0  4.0
    1  3.0  2.0  3.0  3.0
    2  2.0  3.0  2.0  2.0
    3  1.0  4.0  1.0  1.0
    

    【讨论】:

    • 很高兴能帮上忙!您也可以投票 - 点击接受标记上方0 上方的小三角形。谢谢。
    猜你喜欢
    • 2014-11-23
    • 1970-01-01
    • 2021-02-03
    • 2022-11-16
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 2018-08-16
    • 2019-11-01
    相关资源
    最近更新 更多