python pandas 更改DataFrame的行名或列名

更改行名或更改列名可以选用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值