Home > Back-end >  Changing column name and it's values at the same time
Changing column name and it's values at the same time

Time:01-31

Pandas help!

I have a specific column like this,

   Mpg
0   18
1   17
2   19
3   21
4   16
5   15

Mpg is mile per gallon, Now I need to replace that 'MPG' column to 'litre per 100 km' and change those values to litre per 100 km' at the same time. Any help? Thanks beforehand. -Tom

I changed the name of the column but doing both simultaneously,i could not.

CodePudding user response:

Use pop to return and delete the column at the same time and rdiv to perform the conversion (1 mpg = 1/235.15 liter/100km):

df['litre per 100 km'] = df.pop('Mpg').rdiv(235.15)

If you want to insert the column in the same position:

df.insert(df.columns.get_loc('Mpg'), 'litre per 100 km',
          df.pop('Mpg').rdiv(235.15))

Output:

   litre per 100 km
0         13.063889
1         13.832353
2         12.376316
3         11.197619
4         14.696875
5         15.676667

CodePudding user response:

An alternative to pop would be to store the result in another dataframe. This way you can perform the two steps at the same time. In my code below, I first reproduce your dataframe, then store the constant for conversion and perform it on all entries using the apply method.

df = pd.DataFrame({'Mpg':[18,17,19,21,16,15]})

cc = 235.214583 # constant for conversion from mpg to L/100km

df2 = pd.DataFrame()
df2['litre per 100 km'] = df['Mpg'].apply(lambda x: cc/x)

print(df2)

The output of this code is:

   litre per 100 km
0        13.067477
1        13.836152
2        12.379715
3        11.200694
4        14.700911
5        15.680972

as expected.

  • Related