更改行名或更改列名可以选用rename函数。
首先,构建一个dataframe:
import pandas as pd
d={'one':{'a':1,'b':2,'c':3,'d':4},'two':{'a':5,'b':6,'c':7,'d':8},'three':{'a':9,'b':10,'c':11,'d':12}}
df=pd.DataFrame(d)
print(df)
输出结果为:
one two three
a 1 5 9
b 2 6 10
c 3 7 11
d 4 8 12
更改列名
将第2列列名更改为twotwo
df.rename(columns={'two':'twotwo'},inplace=True)
print(df)
输出结果为:
one twotwo three
a 1 5 9
b 2 6 10
c 3 7 11
d 4 8 12
更改行名
将第1行和第2行的行名更改为aa,bb
df.rename(index={'a':'aa','b':'bb'},inplace=True)
print(df)
输出结果为:
one twotwo three
aa 1 5 9
bb 2 6 10
c 3 7 11
d 4 8 12
更改成功。
当然,也可以选择暴力更改行名或列名:
df.columns=['onon','twtw','thth']
print(df)
输出结果为:
onon twtw thth
aa 1 5 9
bb 2 6 10
c 3 7 11
d 4 8 12