Pandas:选择列(使用正则表达式)并重命名它们(使用列表)
Pandas: Selecting columns (with regex) and renaming them (with a list)
我正在尝试在 Python 中做两件事:
- Select 使用
regex
的特定列的名称
- 使用名称列表重命名这些选定的列(不幸的是,这些名称存储在它们自己奇怪的数据框中)
我是 python
和 pandas
的新手,但进行了一系列谷歌搜索,发现 TypeError: Index does not support mutable operations
错误。这就是我正在做的。
import pandas as pd
import numpy as np
df=pd.DataFrame(data=np.array([
[1, 3, 3, 4, 5,9,5],
[1, 2, 4, 4, 5,8,4],
[1, 2, 3, 'a', 5,7,3],
[1, 2, 3, 4, 'e',6,2],
['f', 2, 3, 4, 5,6,1]
]),
columns=[
'a',
'car-b',
'car-c',
'car-d',
'car-e',
'car-f',
'car-g'])
#Select the NAMES of the columns that contain 'car' in them as I want to change these column names
names_to_change = df.columns[df.columns.str.contains("car")]
names_to_change
#Here is the dataset that has the names that I want to use to replace these
#This is just how the names are stored in the workflow
new_names=pd.DataFrame(data=np.array([
['new_1','new_3','new_5'],
['new_2','new_4','new_6']
]))
new_names
#My approach is to transform the new names into a list
new_names_list=pd.melt(new_names).iloc[:,1].tolist()
new_names_list
#Now I figure I would use .columns to do the replacement
#But this returnts the mutability error
df.columns[df.columns.str.contains("car")]=new_names_list
#This also returns the same error
df.columns = df.columns[df.columns.str.contains("car")].tolist()+new_names_list
Traceback (most recent call last):
File "C:\Users\zsg876\AppData\Local\Temp/ipykernel_1340/261138782.py", line 44, in <module>
df.columns[df.columns.str.contains("car")]=new_names_list
File "C:\Users\zsg876\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 4585, in __setitem__
raise TypeError("Index does not support mutable operations")
TypeError: Index does not support mutable operations
我尝试了很多不同的方法(这没有帮助:),但运气不佳。我来自 R
,那里重命名列要简单得多——您只需使用 names()
.
传递一个向量
我认为这里的工作流程不同?感谢任何建议!
更新:
这似乎可以解决问题,但我不确定具体原因。我认为用另一个等长的列表替换一个列表会起作用,但情况似乎并非如此。有人可以在这里教育我吗?
col_rename_dict=dict(zip(names_to_change,new_names_list))
df.rename(columns=col_rename_dict, inplace=True)
您可以使用 df.filter(like='car').columns
获取包含 car
的列的名称,并且您可以使用 new_names.to_numpy().T.ravel
有效地将 new_names
数据帧转换为数组新名字。然后,您可以使用 zip
和 dict
将两个数组转换为字典,其中键是旧列名,值是新列名。然后,使用 axis=1
:
简单地将其传递给 df.rename
old_names = df.filter(like='car').columns
new_names = new_names.to_numpy().T.ravel()
df = df.rename(dict(zip(old_names, new_names)), axis=1)
输出:
>>> df
a new_1 new_2 new_3 new_4 new_5 new_6
0 1 3 3 4 5 9 5
1 1 2 4 4 5 8 4
2 1 2 3 a 5 7 3
3 1 2 3 4 e 6 2
4 f 2 3 4 5 6 1
我正在尝试在 Python 中做两件事:
- Select 使用
regex
的特定列的名称
- 使用名称列表重命名这些选定的列(不幸的是,这些名称存储在它们自己奇怪的数据框中)
我是 python
和 pandas
的新手,但进行了一系列谷歌搜索,发现 TypeError: Index does not support mutable operations
错误。这就是我正在做的。
import pandas as pd
import numpy as np
df=pd.DataFrame(data=np.array([
[1, 3, 3, 4, 5,9,5],
[1, 2, 4, 4, 5,8,4],
[1, 2, 3, 'a', 5,7,3],
[1, 2, 3, 4, 'e',6,2],
['f', 2, 3, 4, 5,6,1]
]),
columns=[
'a',
'car-b',
'car-c',
'car-d',
'car-e',
'car-f',
'car-g'])
#Select the NAMES of the columns that contain 'car' in them as I want to change these column names
names_to_change = df.columns[df.columns.str.contains("car")]
names_to_change
#Here is the dataset that has the names that I want to use to replace these
#This is just how the names are stored in the workflow
new_names=pd.DataFrame(data=np.array([
['new_1','new_3','new_5'],
['new_2','new_4','new_6']
]))
new_names
#My approach is to transform the new names into a list
new_names_list=pd.melt(new_names).iloc[:,1].tolist()
new_names_list
#Now I figure I would use .columns to do the replacement
#But this returnts the mutability error
df.columns[df.columns.str.contains("car")]=new_names_list
#This also returns the same error
df.columns = df.columns[df.columns.str.contains("car")].tolist()+new_names_list
Traceback (most recent call last):
File "C:\Users\zsg876\AppData\Local\Temp/ipykernel_1340/261138782.py", line 44, in <module>
df.columns[df.columns.str.contains("car")]=new_names_list
File "C:\Users\zsg876\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 4585, in __setitem__
raise TypeError("Index does not support mutable operations")
TypeError: Index does not support mutable operations
我尝试了很多不同的方法(这没有帮助:R
,那里重命名列要简单得多——您只需使用 names()
.
我认为这里的工作流程不同?感谢任何建议!
更新:
这似乎可以解决问题,但我不确定具体原因。我认为用另一个等长的列表替换一个列表会起作用,但情况似乎并非如此。有人可以在这里教育我吗?
col_rename_dict=dict(zip(names_to_change,new_names_list))
df.rename(columns=col_rename_dict, inplace=True)
您可以使用 df.filter(like='car').columns
获取包含 car
的列的名称,并且您可以使用 new_names.to_numpy().T.ravel
有效地将 new_names
数据帧转换为数组新名字。然后,您可以使用 zip
和 dict
将两个数组转换为字典,其中键是旧列名,值是新列名。然后,使用 axis=1
:
df.rename
old_names = df.filter(like='car').columns
new_names = new_names.to_numpy().T.ravel()
df = df.rename(dict(zip(old_names, new_names)), axis=1)
输出:
>>> df
a new_1 new_2 new_3 new_4 new_5 new_6
0 1 3 3 4 5 9 5
1 1 2 4 4 5 8 4
2 1 2 3 a 5 7 3
3 1 2 3 4 e 6 2
4 f 2 3 4 5 6 1