pandas 修改 DataFrame 列名

简介: 问题:有一个DataFrame,列名为:['$a', '$b', '$c', '$d', '$e']现需要改为:['a', 'b', 'c', 'd', 'e']有何办法?import pandas as pddf = pd.

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

import pandas as pd
df = pd.DataFrame({'$a': [1], '$b': [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', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}, inplace=True) 

# ⑤修改
df.rename(columns=lambda x:x.replace('$',''), inplace=True)
目录
相关文章
|
5月前
|
机器学习/深度学习 Python
pandas将dataframe列中的list转换为多列
在应用机器学习的过程中,很大一部分工作都是在做数据的处理,一个非常常见的场景就是将一个list序列的特征数据拆成多个单独的特征数据。
117 0
|
11月前
dataframe获取指定列
dataframe获取指定列
755 0
|
26天前
|
SQL 索引 Python
Pandas中DataFrame合并的几种方法
Pandas中DataFrame合并的几种方法
84 0
|
2月前
|
索引 Python
如何在 Pandas 数据框中添加新列?
【8月更文挑战第30天】
214 4
|
1月前
|
数据采集 机器学习/深度学习 数据处理
DataFrame 操作
DataFrame 操作
83 1
|
2月前
|
索引 Python
Pandas 中的重新索引
【8月更文挑战第30天】
37 1
|
4月前
|
Python
在Python的pandas库中,向DataFrame添加新列简单易行
【6月更文挑战第15天】在Python的pandas库中,向DataFrame添加新列简单易行。可通过直接赋值、使用Series或apply方法实现。例如,直接赋值可将列表或Series对象分配给新列;使用Series可基于现有列计算生成新列;apply方法则允许应用自定义函数到每一行或列来创建新列。
414 8
|
存储 数据处理 索引
【如何在 Pandas DataFrame 中插入一列】
【如何在 Pandas DataFrame 中插入一列】
130 0
|
数据挖掘 索引 Python
【Python数据分析 - 11】:DataFrame索引操作(pandas篇)
【Python数据分析 - 11】:DataFrame索引操作(pandas篇)
260 0
【Python数据分析 - 11】:DataFrame索引操作(pandas篇)
Pandas 已有 DataFrame,给其加列名
Pandas 已有 DataFrame,给其加列名