简体   繁体   English

重命名python数据框中的条件列

[英]Rename columns on condition in python data frame

I have a column in python dataframe which will be either _00_test or 00_test . 我在python数据_00_test有一个列,它将是_00_test00_test I want to rename the column to test. 我想重命名要测试的列。

What I want to do is check columns in data frame if either _00_test or 00_test is present then rename the column name as test 我想做的是检查数据框中的列是否存在_00_test00_test ,然后将列名重命名为test

How to do that? 怎么做?

DataFrame.rename will not fail if the column is not in the dataframe. 如果列不在数据DataFrame.renameDataFrame.rename不会失败。 So if we assume exclusivity, only one of the columns can exist in the dataframe, then you can do that in one go:: 因此,如果我们假设排他性,则数据框中只能存在一列,那么您可以一口气做到这一点:

>>> import pandas as pd
>>> df = pd.DataFrame({'_00_test': range(5)})
>>> df
   _00_test
0         0
1         1
2         2
3         3
4         4
>>> df.rename(columns={'_00_test': 'test', '00_test': 'test'})
   test
0     0
1     1
2     2
3     3
4     4

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

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