问题: 有一个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)
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
df.columns = df.columns.map(lambda x:x.lower())