2

I have a column in python dataframe which will be either _00_test or 00_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

How to do that?

1 Answer 1

4

DataFrame.rename will not fail if the column is not in the dataframe. 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.