熊猫-如何根据索引位置重命名特定的列

凯文·纳什(Kevin Nash)

我正在尝试重命名Pandas DataFrame中的几列。但是,我遇到的问题是有多个具有相同名称的列,因此,当我尝试重命名具有名称的所有列时,将被重命名。但是我只想重命名特定的列(按索引位置)。

以下是列名:

customer_name, customer_address, customer_profile, customer_address

我想将出现在索引1中的列“ customer_address”重命名为“ address”

当我在下面尝试时,两个带有标签的列都customer_address被重命名为address

df.rename(columns={df.columns[1]: "address"}, inplace = True)
耶斯列尔

第一个想法是按位置设置numpy数组:

df.columns.to_numpy()[1] = 'address'
#old pandas versions
#df.columns.values[1] = 'address'
print (df)
Empty DataFrame
Columns: [customer_name, address, customer_profile, customer_address]
Index: []

另一个想法是更改从列名创建的numpy数组:

arr = df.columns.to_numpy()
arr[1] = 'address'
df.columns = arr
print (df)
Empty DataFrame
Columns: [customer_name, address, customer_profile, customer_address]
Index: []

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章