2

My df looks like this:

Datum Zeit Temperatur[°C] Luftdruck Windgeschwindigkeit[m/s] Windrichtung[Grad] Relative Luftfeuchtigkeit[%] Globalstrahlung[W/m²] 

Now i want to rename the columns like this:#

wetterdaten.rename(columns={'Temperatur%': 'Temperatur', 'Luftdruck[hPa]': 'Luftdruck'}, inplace=True) 

Where % is a wildcard. But of course it will not work like this.

The beginning of the column name is always the same in the log data, but the ending is temporally changing.

0

4 Answers 4

5

You can filter the columns and fetch the name:

wetterdaten.rename(columns={wetterdaten.filter(regex='Temperatur.*').columns[0]: 'Temperatur', wetterdaten.filter(regex='Luftdruck.*').columns[0]: 'Luftdruck'}, inplace=True) 
Sign up to request clarification or add additional context in comments.

Comments

4

You can use replace by dict, for wildcard use .* and for start of string ^:

d = {'^Temperatur.*': 'Temperatur', 'Luftdruck[hPa]': 'Luftdruck'} df.columns = df.columns.to_series().replace(d, regex=True) 

Sample:

cols = ['Datum', 'Zeit', 'Temperatur[°C]', 'Luftdruck' , 'Windgeschwindigkeit[m/s]', 'Windrichtung[Grad]', 'Relative Luftfeuchtigkeit[%]', ' Globalstrahlung[W/m²]'] df = pd.DataFrame(columns=cols) print (df) Empty DataFrame Columns: [Datum, Zeit, Temperatur[°C], Luftdruck, Windgeschwindigkeit[m/s], Windrichtung[Grad], Relative Luftfeuchtigkeit[%], Globalstrahlung[W/m²]] Index: [] d = {'^Temperatur.*': 'Temperatur', 'Luftdruck.*': 'Luftdruck'} df.columns = df.columns.to_series().replace(d, regex=True) print (df) Empty DataFrame Columns: [Datum, Zeit, Temperatur, Luftdruck, Windgeschwindigkeit[m/s], Windrichtung[Grad], Relative Luftfeuchtigkeit[%], Globalstrahlung[W/m²]] Index: [] 

2 Comments

That is not what i want.
@kolja could you explain why this is not the result that you want? Because it looks to me this is exactly the result you wanted.
1

You may prepare a function for renaming you columns:

rename_columns(old_name): if old_name == 'Temperatur': new_name = old_name + whichever_you_wants # may be another function call elif old_name == 'Luftdruck': new_name = 'Luftdruck[hPa]' else: new_name = old_name return new_name 

and then use the .rename() method with that function as a parameter:

wetterdaten.rename(columns=rename_columns, inplace=True) 

1 Comment

This might not be exactly what OP needed, but it is exactly what I need. And it is by far the cleanest solution. Nice!
0

Also, you can try the below code; Which replaces #Item Code into Item Name without condition.

Code:

pd.rename(columns = {'#Item Code':'Item Name'}, inplace = True) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.