本文介绍了更改多个列名但不是全部 - 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.

推荐答案

假设您有一个包含新列名称和它们应该替换的列名称的字典:

say you have a dictionary of the new column names and the name of the column they should replace:

df.rename(columns={'old_col':'new_col', 'old_col_2':'new_col_2'}, inplace=True)

但是,如果你没有那个,而你只有索引,你可以这样做:

But, if you don't have that, and you only have the indices, you can do this:

column_indices = [1,4,5,6]
new_names = ['a','b','c','d']
old_names = df.columns[column_indices]
df.rename(columns=dict(zip(old_names, new_names)), inplace=True)

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

10-21 11:26