简体   繁体   English

通过搜索列表替换 Pandas DF 列

[英]Replacing Pandas DF columns by searching through a list

I am working on a problem where I have a dataframe which contains data along with the columns names which are codes for some specific purpose as below:我正在解决一个问题,我有一个 dataframe,它包含数据以及列名,这些列名是用于某些特定目的的代码,如下所示:

AB_01 AB_01 AB_12 AB_12 AB_32 AB_32 AB_50 AB_50
John约翰 26 26 E1 E1 US我们
Tina蒂娜 30 30 E2 E2 CA加州
Michael迈克尔 50 50 E1 E1 UK英国
Shaw邵氏 55 55 E3 E3 US我们

I have a list of list which contains column names along with their corresponding column codes as below:我有一个列表列表,其中包含列名及其相应的列代码,如下所示:

[
  ['AB_01', 'Name']
  ['AB_12', 'Age']  
  ['AB_32', 'Unit']  
  ['AB_50', 'Country']
  ['BZ_90', 'Zip']
  ['CX_10', 'State']
  ['ED_55', 'Email']
]

Some of the columns might not be used in the dataframes so I'd like to search for the column codes from the list and then replace the column codes with the names in the list so that I have something like below:某些列可能未在数据框中使用,因此我想从列表中搜索列代码,然后将列代码替换为列表中的名称,以便我得到如下所示的内容:

Name名称 Age年龄 Unit单元 Country国家
John约翰 26 26 E1 E1 US我们
Tina蒂娜 30 30 E2 E2 CA加州
Michael迈克尔 50 50 E1 E1 UK英国
Shaw邵氏 55 55 E3 E3 US我们

What would be the best way of doing this?这样做的最好方法是什么? The one I think of is iterating through each column code in the dataframe, comparing it with the column code in the list and then replacing it with the corresponding column name from the list.我想到的是遍历 dataframe 中的每一列代码,将其与列表中的列代码进行比较,然后将其替换为列表中相应的列名称。 Is there a better way of doing it?有更好的方法吗?

You can convert the list to a dictionary and map it to the columns:您可以将列表转换为字典,并将map转换为列:

df.columns = df.columns.map(dict(lst))

Output: Output:

      Name  Age Unit Country
0     John   26   E1      US
1     Tina   30   E2      CA
2  Michael   50   E1      UK
3     Shaw   55   E3      US

Let us try rename , l is your list让我们尝试renamel是您的列表

out = df.rename(columns = dict(l))
Out[332]: 
      Name  Age Unit Country
0     John   26   E1      US
1     Tina   30   E2      CA
2  Michael   50   E1      UK
3     Shaw   55   E3      US

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM