pandas 修改 DataFrame 列名

    科技2025-09-03  20

    pandas 修改 DataFrame 所有列名为小写

    pandas 修改 DataFrame 列名①暴力②修改③修改④暴力(好处:也可只修改特定的列)⑤修改 Python 字符串大小写转换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())

    Processed: 0.026, SQL: 8