Home > Enterprise >  Add dictionary values to dataframe column names
Add dictionary values to dataframe column names

Time:06-13

With this dataframe df

   a  b  c 
0  x  x  x
1  x  x  x
2  x  x  x

and this dictionary

headers = {'a' : '3.14', 'b' : '6.67', 'c' : '8.31'}

df = df.rename(headers) allows to rename the column names as such

   3.14  6.67  8.31 
0     x     x     x
1     x     x     x
2     x     x     x

How to just add the dictionary values to the column names? Like this:

   a 3.14  b 6.67  c 8.31 
0       x       x       x
1       x       x       x
2       x       x       x

CodePudding user response:

Try with lambda

df = df.rename(columns = lambda x : x   ' '    headers.get(x))
Out[613]: 
  a 3.14 b 6.67 c 8.31
0      x      x      x
1      x      x      x
2      x      x      x

CodePudding user response:

You can create a new dictionary based on headers

df = df.rename(columns={col: f'{col} {num}' for col, num in headers.items()})

Output:

>>> df

  a 3.14 b 6.67 c 8.31
0      x      x      x
1      x      x      x
2      x      x      x

CodePudding user response:

Why not change the dict before,

headers = {'a' : '3.14', 'b' : '6.67', 'c' : '8.31'}

for key, value in headers.items():
    headers[key] = key   " "   value
    
print(headers)

CodePudding user response:

A slightly different lambda expression with f string,

df.rename(columns=lambda x: f"x {headers[x]}")
  • Related