pandas 修改 DataFrame 列名

pandas 修改 DataFrame 列名

问题:
有一个DataFrame,列名为:[‘ a ′ , ′ a', ' a,b’, ‘ c ′ , ′ c', ' c,d’, ‘$e’]
现需要改为:[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
有何办法?

import pandas as pd
df = pd.DataFrame({‘ a ′ : [ 1 ] , ′ a': [1], ' a:[1],b’: [1], ‘ c ′ : [ 1 ] , ′ c': [1], ' c:[1],d’: [1], ‘$e’: [1]})
解决:

方式一:columns属性

①暴力

df.columns = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

②修改

df.columns = df.columns.str.strip(’$’)

③修改

df.columns = df.columns.map(lambda x:x[1:])
方式二:rename方法、columns参数

④暴力(好处:也可只修改特定的列)

df.rename(columns=(‘ a ′ : ′ a ′ , ′ a': 'a', ' a:a,b’: ‘b’, ‘ c ′ : ′ c ′ , ′ c': 'c', ' c:c,d’: ‘d’, ‘$e’: ‘e’}, inplace=True)

⑤修改

df.rename(columns=lambda x:x.replace(’$’,’’), inplace=True)

Python 字符串大小写转换

str = “www.runoob.com”
print(str.upper()) # 把所有字符中的小写字母转换成大写字母
print(str.lower()) # 把所有字符中的大写字母转换成小写字母
print(str.capitalize()) # 把第一个字母转化为大写字母,其余小写
print(str.title()) # 把每个单词的第一个字母转化为大写,其余小写
执行以上代码输出结果为:

WWW.RUNOOB.COM
www.runoob.com
Www.runoob.com
Www.Runoob.Com

pandas 修改 DataFrame 所有列名为小写

df.columns = df.columns.map(lambda x:x.lower())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值