更改多个列名,但不能全部更改-Pandas Python [英] Changing multiple column names but not all of them - Pandas Python

查看:45
本文介绍了更改多个列名,但不能全部更改-Pandas Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一个功能可以更改特定的列名,但无需选择特定的名称或不更改所有的列名.

I would like to know if there is a function to change specific column names but without selecting a specific name or without changing all of them.

我有代码:

df=df.rename(columns = {'nameofacolumn':'newname'})

但是,我必须手动更改其中每个人的名字. 还要更改所有我拥有的

But with it i have to manually change each one of them writing each name. Also to change all of them I have

df = df.columns['name1','name2','etc']

我想有一个功能来更改第1列和第3列,而不必写它们的名称,而只是说明它们的位置.谢谢!

I would like to have a function to change columns 1 and 3 without writing their names just stating their location. Thanks!

推荐答案

您可以使用dict理解并将其传递给rename:

You can use a dict comprehension and pass this to rename:

In [246]:
df = pd.DataFrame(columns=list('abc'))
new_cols=['d','e']
df.rename(columns=dict(zip(df.columns[1:], new_cols)),inplace=True)
df

Out[246]:
Empty DataFrame
Columns: [a, d, e]
Index: []

如果您传递顺序位置列表,它也将起作用:

It also works if you pass a list of ordinal positions:

df.rename(columns=dict(zip(df.columns[[1,2]], new_cols)),inplace=True)

这篇关于更改多个列名,但不能全部更改-Pandas Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆