2013-04-10 85 views
0

我有一个数据框,我想更改列名。目前我正在使用下面的方法,包括转置,重新索引和移调回来。即使世界必须是一个简单的方法.....将更改应用于数据帧的列名

任何建议表示赞赏

import pandas as pd 

#make a dataframe with wacky column names 
d = {'garbled #### one' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']), 
    'garbled ### two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])} 
df = pd.DataFrame(d) 

#fix the column names by transposing, reseting index, string manipulation, 
#and transposing back 
df = df.T 
df = df.reset_index() 
df['index'] = df['index'].apply(lambda x: x.split()[0]+ " " +x.split()[2]) 
df = df.set_index('index') 
df = df.T 
df 

index garbled two garbled one 
a 1 1 
b 2 2 
c 3 3 
d 4 4 

感谢, 扎克CP

回答

2

rename_axis允许重命名而不创建/删除列。重命名可以使用函数或一对一映射(类似于字典)来完成,映射可以是部分的(不必包含所有名称)。

In [42]: df 
Out[42]: 
    garbled #### one garbled #### two 
a     1     1 
b     2     2 
c     3     3 
d     4     4 

In [43]: df.rename_axis(lambda x: x.split()[0]+ " " +x.split()[2]) 
Out[43]: 
    garbled one garbled two 
a   1   1 
b   2   2 
c   3   3 
d   4   4 

In [44]: df.rename_axis({'garbled #### one': 'one', 'garbled #### two': 'two'}) 
Out[44]: 
    one two 
a 1 1 
b 2 2 
c 3 3 
d 4 4 
+0

这正是我正在寻找的,谢谢。 – zach 2013-04-10 18:19:48

1

也许我低估了这个问题,但这里是一个相当琐碎方法。

获取列名与列表(真是pd.Index):

df.columns 

遍历列名,看是否有乱码。如果您发现有乱码名称的列,创建一个好名字的新列,并删除旧的一列,例如:

df["good-one"] = df["garbled #### one"] 
del df["garbled #### one"] 

除非该表是巨大的,复制的数据量是一个问题,这将起作用。

+0

这是一个简单且完全忽略的解决方案。 (doh!)我曾尝试过df.columns [0] < - '乱码',这是行不通的,因为索引是不可变的。 – zach 2013-04-10 15:36:54