['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
使用df.rename()
函数并引用要重命名的列。并非所有列都需要重命名:
df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})
# Or rename the existing DataFrame (rather than creating a copy)
df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)
最简代码示例
df = pd.DataFrame('x', index=range(3), columns=list('abcde'))
df
a b c d e
0 x x x x x
1 x x x x x
2 x x x x x
df2 = df.rename({'a': 'X', 'b': 'Y'}, axis=1)
df2 = df.rename({'a': 'X', 'b': 'Y'}, axis='columns')
df2 = df.rename(columns={'a': 'X', 'b': 'Y'})
df2
X Y c d e
0 x x x x x
1 x x x x x
2 x x x x x
inplace=True
:df.rename({'a': 'X', 'b': 'Y'}, axis=1, inplace=True)
df
X Y c d e
0 x x x x x
1 x x x x x
2 x x x x x
errors='raise'
来指定,如果指定了无效的要重命名的列,则会引发错误。
使用df.set_axis()
和axis=1
。
df2 = df.set_axis(['V', 'W', 'X', 'Y', 'Z'], axis=1)
df2
V W X Y Z
0 x x x x x
1 x x x x x
2 x x x x x
df.columns = ['V', 'W', 'X', 'Y', 'Z']
df
V W X Y Z
0 x x x x x
1 x x x x x
2 x x x x x
code
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000 entries, 0 to 999
Data columns:
BodyMarkdown 1000 non-null。使用 code
可以正常工作,但是当我使用 dataframe.head() 函数时,旧列名会重新出现。 - darKoramSettingWithCopyWarning:
警告。 - Monica Heddneckdf = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})
更改了显示的名称,但没有更改底层数据结构中的元素。因此,如果您尝试df['newName1']
,将会出现一个错误。inplace=True
是必要的,以避免这种问题。 - irritable_phd_syndromedf = df.copy().rename(columns={'old':'new_name'})
。这意味着首先要复制整个数据框,进行重命名,然后将其分配,完全覆盖原始数据框。 - gseattle只需将其分配给.columns
属性:
>>> df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})
>>> df
$a $b
0 1 10
1 2 20
>>> df.columns = ['a', 'b']
>>> df
a b
0 1 10
1 2 20
new_columns = df.columns.values;
new_columns[0] = 'XX';
df.columns = new_columns
- cd98df.rename(columns={'$b':'B'}, inplace=True)
。该代码用于将 Pandas 数据框 df 中名为 "$b" 的列重命名为 "B",并直接在原数据框上进行修改。 - nachocabrename
方法可以接收一个函数作为参数,例如:
In [11]: df.columns
Out[11]: Index([u'$a', u'$b', u'$c', u'$d', u'$e'], dtype=object)
In [12]: df.rename(columns=lambda x: x[1:], inplace=True)
In [13]: df.columns
Out[13]: Index([u'a', u'b', u'c', u'd', u'e'], dtype=object)
df.rename(columns=lambda x: x.lstrip(), inplace=True)
。 - root-11t.columns = t.columns.str.replace(r'[^\x00-\x7F]+','')
。 - Nate Andersondf.rename(columns=lambda x: x.replace(' ', '_'), inplace=True)
是一条好的命令,它使我们能够写 df.Column_1_Name
而不是写 df.loc[:, 'Column 1 Name']
。 - Little Bobby Tablesdf.rename(columns=str.lstrip)
- Ian Liu Rodrigues在版本0.21中,列重命名有了一些重大更新。
rename
方法添加了axis
参数,可以设置为columns
或1
。此更新使该方法与pandas API的其余部分匹配。它仍然具有index
和columns
参数,但您不再被强制使用它们。set_axis
方法将inplace
设置为False
,使您能够使用列表重命名所有索引或列标签。构造示例DataFrame:
df = pd.DataFrame({'$a':[1,2], '$b': [3,4],
'$c':[5,6], '$d':[7,8],
'$e':[9,10]})
$a $b $c $d $e
0 1 3 5 7 9
1 2 4 6 8 10
rename
和axis='columns'
或axis=1
df.rename({'$a':'a', '$b':'b', '$c':'c', '$d':'d', '$e':'e'}, axis='columns')
或者
df.rename({'$a':'a', '$b':'b', '$c':'c', '$d':'d', '$e':'e'}, axis=1)
a b c d e
0 1 3 5 7 9
1 2 4 6 8 10
仍然可以使用旧的方法签名:
df.rename(columns={'$a':'a', '$b':'b', '$c':'c', '$d':'d', '$e':'e'})
rename
函数还接受应用于每个列名的函数。
df.rename(lambda x: x[1:], axis='columns')
或者
df.rename(lambda x: x[1:], axis=1)
inplace=False
的set_axis
方法您可以向set_axis
方法提供与列数(或索引)相等长度的列表。目前,inplace
默认为True
,但在未来的版本中,inplace
将默认为False
。
df.set_axis(['a', 'b', 'c', 'd', 'e'], axis='columns', inplace=False)
或者
df.set_axis(['a', 'b', 'c', 'd', 'e'], axis=1, inplace=False)
df.columns = ['a', 'b', 'c', 'd', 'e']
?直接这样分配列没有问题,是一个完全可行的解决方案。
使用set_axis
的优点是它可以作为方法链的一部分使用,并且它返回DataFrame的新副本。如果不使用它,则必须将链的中间步骤存储到另一个变量中,然后重新分配列。
# new for pandas 0.21+
df.some_method1()
.some_method2()
.set_axis()
.some_method3()
# old way
df1 = df.some_method1()
.some_method2()
df1.columns = columns
df1.some_method3()
Pandas 0.21+ answer
- 不知何故,我在“新功能”部分错过了那一部分... - MaxU - stand with Ukraine(df
.groupby(['page',pd.Grouper(key='date',freq='MS')])['clicks'].sum()
.unstack(1)
.rename(lambda x: x.strftime("%Y-%m"), axis='columns')
)
- measureallthethings如果您只想在所有列名称中删除美元符号,您可以这样做:
df = df.rename(columns=lambda x: x.replace('$', ''))
或者
df.rename(columns=lambda x: x.replace('$', ''), inplace=True)
Pandas中重命名列是一项简单的任务。
df.rename(columns={'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}, inplace=True)
columns
参数也可以是一个函数。因此,如果您想从每个名称中删除第一个字符,可以执行 df.rename(columns=lambda name: name[1:], inplace=True)
(参考)。 - aschmieddf.columns = ['a', 'b', 'c', 'd', 'e']
它将按照您提供的顺序,使用您提供的名称替换现有名称。
df.columns.values
,这是错误的。https://dev59.com/KlgQ5IYBdhLWcg3wGgP0 - llllllllll使用:
old_names = ['$a', '$b', '$c', '$d', '$e']
new_names = ['a', 'b', 'c', 'd', 'e']
df.rename(columns=dict(zip(old_names, new_names)), inplace=True)
通过这种方式,您可以手动编辑new_names
,使其符合您的要求。当您仅需更改少量列名以纠正拼写错误、重音、删除特殊字符等情况时,它非常有效。
df.columns = ['a', 'b', 'c', 'd', 'e']
更简单。 - Christopher Pearsondf.columns.values
来获取旧名称。 - bkowshikmyList = list(df) myList[10:20]
,等等 - 所以这非常完美。 - Tim Gottgetreunamez = df.columns.values
接着进行一些编辑,然后df.columns = namez
。 - pauljohn32我将关注两件事:
OP明确说明:
我已经将编辑后的列名存储在一个列表中,但我不知道如何替换列名。
我不想解决如何替换'$'
或去掉每个列头的第一个字符的问题。 OP已经完成了这一步。 我想专注于根据替换列名的列表替换现有的columns
对象。
df.columns = new
,其中new
是新列名列表,这是最简单的方法。 这种方法的缺点是它需要编辑现有数据框的columns
属性,并且它不能直接完成。 我将展示一些通过流水线执行此操作的方法,而无需编辑现有的数据框。
设置1
为了关注使用预先存在的列表重命名或替换列名的必要性,我将创建一个新的示例数据框df
,其中包含初始列名和不相关的新列名。
df = pd.DataFrame({'Jack': [1, 2], 'Mahesh': [3, 4], 'Xin': [5, 6]})
new = ['x098', 'y765', 'z432']
df
Jack Mahesh Xin
0 1 3 5
1 2 4 6
解决方案1
pd.DataFrame.rename
已经有人说过,如果你有一个将旧列名映射到新列名的字典,那么你可以使用 pd.DataFrame.rename
。
d = {'Jack': 'x098', 'Mahesh': 'y765', 'Xin': 'z432'}
df.rename(columns=d)
x098 y765 z432
0 1 3 5
1 2 4 6
rename
的调用中。以下代码利用了这样一个事实,即当迭代df
时,我们会遍历每个列名。# Given just a list of new column names
df.rename(columns=dict(zip(df, new)))
x098 y765 z432
0 1 3 5
1 2 4 6
如果您原始的列名是唯一的,则此方法非常有效。但是,如果它们不是唯一的,则无法使用此方法。
设置2
非唯一列
df = pd.DataFrame(
[[1, 3, 5], [2, 4, 6]],
columns=['Mahesh', 'Mahesh', 'Xin']
)
new = ['x098', 'y765', 'z432']
df
Mahesh Mahesh Xin
0 1 3 5
1 2 4 6
解决方案 2
使用pd.concat
函数和keys
参数
首先,注意当我们尝试使用解决方案 1 时会发生什么:
df.rename(columns=dict(zip(df, new)))
y765 y765 z432
0 1 3 5
1 2 4 6
pd.concat([c for _, c in df.items()], axis=1, keys=new)
x098 y765 z432
0 1 3 5
1 2 4 6
解决方案三
重构。只有在所有列使用相同的 dtype
时才应该使用此方法。否则,您将得到所有列的 dtype
为 object
,并且将它们转换回来需要更多的字典工作。
单一 dtype
pd.DataFrame(df.values, df.index, new)
x098 y765 z432
0 1 3 5
1 2 4 6
混合数据类型
pd.DataFrame(df.values, df.index, new).astype(dict(zip(new, df.dtypes)))
x098 y765 z432
0 1 3 5
1 2 4 6
解决方案4
这是一个使用transpose
和set_index
的花哨技巧。 pd.DataFrame.set_index
允许我们在内联中设置索引,但没有相应的set_columns
。所以我们可以进行转置,然后set_index
,再次转置回来。但是,与解决方案3相同的单个dtype
与混合dtype
的注意事项也适用于此处。
单个dtype
df.T.set_index(np.asarray(new)).T
x098 y765 z432
0 1 3 5
1 2 4 6
混合数据类型
df.T.set_index(np.asarray(new)).T.astype(dict(zip(new, df.dtypes)))
x098 y765 z432
0 1 3 5
1 2 4 6
pd.DataFrame.rename
中的lambda
循环遍历new
的每个元素。lambda
,它接受x
但忽略它。它还接受y
,但不需要它。相反,迭代器作为默认值给出,然后我可以使用它以无需考虑x
的值来逐个循环遍历。df.rename(columns=lambda x, y=iter(new): next(y))
x098 y765 z432
0 1 3 5
1 2 4 6
正如sopython聊天室的人指出的那样,如果在x
和y
之间添加一个*
,就可以保护我的y
变量。虽然在这种情况下我不认为它需要保护,但还是值得一提。
df.rename(columns=lambda x, *, y=iter(new): next(y))
x098 y765 z432
0 1 3 5
1 2 4 6
df.rename(lambda x : x.lstrip('$'),axis=1)
。 - BENY