在Pandas DataFrame中部分重命名列 [英] Partially Renaming Columns in Pandas DataFrame
本文介绍了在Pandas DataFrame中部分重命名列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试重命名DataFrame的前N列.
I'm trying to rename the first N columns of a DataFrame.
import pandas as pd
Dat = pd.read_csv(inputName, delimiter='\t', header=0)
原始表格如下:
$Date $ciq_ticker $industry price ...
'09/30/2016 'AAPL' 'Technology' 100.00
'09/30/2016 'AMZN' 'Consumer' 1000.00
...
我想使某些列名称更直观.我的想法是这样的:
I want to make some column names more intuitive. What's in my mind is something like this:
descriptors = ['date','ticker','industry']
Dat.columns[:len(descriptors)] = descriptors
这将导致错误索引不支持可变操作".
This gives an error of "Index does not support mutable operations".
我知道类似的作品:
Dat.rename(columns={'$Date': 'date', '$ciq_ticker': 'ticker', '$industry': 'industry'}, inplace=True)
但是我只是不喜欢必须显式键入原始列名的想法.事实是,实际表有20列以上我需要修改.
But I just don't like the idea of having to type the original column names explicitly. Truth is, the real table has more than 20 columns that I need to modify.
推荐答案
尝试一下:
In [91]: cols = ['date','ticker','industry']
In [92]: df
Out[92]:
$Date $ciq_ticker $industry price
0 09/30/2016 AAPL Technology 100.0
1 09/30/2016 AMZN Consumer 1000.0
In [93]: df.columns = cols + df.columns.tolist()[len(cols):]
In [94]: df
Out[94]:
date ticker industry price
0 09/30/2016 AAPL Technology 100.0
1 09/30/2016 AMZN Consumer 1000.0
这篇关于在Pandas DataFrame中部分重命名列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文