【问题标题】:Rename dataframe columns using pandas python [duplicate]使用pandas python重命名数据框列[重复]
【发布时间】:2018-04-02 18:24:48
【问题描述】:

我正在尝试更改我的数据框列名称,我尝试了两种方法,但都没有奏效。 这是我的代码;

方法一:

def func():   
    energy=pd.ExcelFile('Energy Indicators.xls').parse('Energy')
    energy=energy.iloc[16:][['Environmental Indicators: Energy','Unnamed:3','Unnamed: 4','Unnamed: 5']].copy() energy.columns()=['Country',
    'Energy Supply', 'Energy Supply per Capita', '%Renewable']
return energy

方法二:

def func():
    energy=pd.ExcelFile('Energy Indicators.xls').parse('Energy')
    energy=energy.iloc[16:][['Environmental Indicators: Energy','Unnamed: 3','Unnamed: 4','Unnamed: 5']].copy()

    return energy.rename(columns={'Environmental Indicators: Energy': 'Country', 'Unnamed: 3': 'Energy Supply',
                                  'Unnamed: 4': 'Energy Supply per Capita', 'Unnamed: 5': '% Renewable'}, inplace=True)

它们都返回一个 NoneType 对象。

这是我正在处理的 .xls 文件:https://drive.google.com/file/d/0B80lepon1RrYeDRNQVFWYVVENHM/view?usp=sharing

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    inplace=True 参数修改数据框,这意味着它不会返回任何操作结果。

    您可以:
    - 返回.rename() 不带inplace=True,或
    - 不返回任何内容并使用传递引用属性进行更新。

    【讨论】:

      【解决方案2】:

      在方法一中,尝试将energy.columns()改为energy.columns

      energy.columns =['Country','Energy Supply', 'Energy Supply per Capita', '%Renewable']
      

      【讨论】:

      • 不错!感谢您的回答
      猜你喜欢
      • 2019-03-03
      • 2012-08-25
      • 1970-01-01
      • 2019-02-19
      • 2018-09-23
      • 2019-09-26
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      相关资源
      最近更新 更多