I'm importing a excel file into python with pd.read_excel()
The columns names in the file like this :
columns_name_xlsx = ['Date:', 'Heure:','P1 (W)', 'P2 (W)', 'P3 (W)']
I would like to get :
columns_name_expected = ['date:', 'heure:','p1_(w)', 'p2_(w)', 'p3_(w)']
I tried with :
df.rename(str.lower.replace(' ', '_'), axis='columns')
But it does not work. Does sb have an idea ?
Thanks !
CodePudding user response:
df.columns = (x.lower().replace(' ', '_') for x in df.columns)
CodePudding user response:
Your solution does not work because
- You are trying to chain two methods which is not really possible
- The replace methods requires to provide arguments (
' '
and_
)
Assuming this DataFrame exists
# Build mock dataframe
df = pd.DataFrame(columns=['Date:', 'Heure:', 'P1 (W)', 'P2 (W)', 'P3 (W)'])
The simplest method is to iteratively apply a transformation on the initial column name as such
df1 = df.rename(columns={v: v.lower().replace(' ', '_') for v in df.columns})
Alternatively, you could chain operations and build a custom function
df1 = df.rename(str.lower, axis=1).rename(lambda x: x.replace(' ', '_'), axis=1)
I hope that helps!