Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pandas renaming column name startswith

i have multiple excel files with uniform column names, except for one.

One file calls it EndOfMarchStatus, another file calls it EndofAprilStatus, and so on.

i need to change the column name to just say EndofMonthStatus. there really is no answer i could find that matches this question.

some form of rename command with wildcards or startswith will probably work.

things i've tried but did not work are:

sheet1df.columns.str.replace('Endof.*', 'EndOfMonthStatus')

sheet1df.rename(columns={sheet1df.filter(regex='*.Status').columns[0]: 'EndOfMonthStatus'}, inplace=True)

sheet1df.rename(columns={'^Status':'EndOfMonthStatus'}, inplace=True)

sheet1df.rename(columns=lambda x: x.replace('Endof%', 'EndOfMonthStatus'), inplace=True)  
like image 433
Juliet A Avatar asked Nov 05 '25 05:11

Juliet A


1 Answers

You can do it like this:

df = pd.DataFrame({"A":[1,2,3], "EndOfApril":[2,3,4]})
df.rename(columns = { i: "EndOfMonth" for i in  df.columns if i.startswith("EndOf") } )

outputs:

    A   EndOfMonth
0   1   2
1   2   3
2   3   4
like image 160
Christian Sloper Avatar answered Nov 06 '25 19:11

Christian Sloper