我有一个数据帧,我想要更改列名。目前我正在使用下面的方法,它涉及转置,重新索引和转置回来。一定有更简单的方法……
如有任何建议,欢迎光临。
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谢谢,zach cp
发布于 2013-04-11 01:55:55
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发布于 2013-04-10 23:31:47
也许我低估了这个问题,但这里有一个相当简单的方法。
使用以下命令获取列名列表(实际上是一个pd.Index):
df.columns遍历列名,看看是否有乱码。如果发现一个名称乱码的列,请创建一个名称正确的新列,然后删除旧列,如下所示:
df["good-one"] = df["garbled #### one"]
del df["garbled #### one"]除非表很大,并且复制的数据量是一个问题,否则这将是可行的。
https://stackoverflow.com/questions/15929220
复制相似问题