Write a program in Python Pandas to convert a dataframe Celsius data column into Fahrenheit

In this tutorial, we'll learn how to convert a Celsius column to Fahrenheit in a Pandas DataFrame. The conversion formula is: Fahrenheit = (9/5) × Celsius + 32.

We'll explore two common approaches using assign() and apply() methods.

Using assign() Method

The assign() method creates a new column while keeping the original DataFrame unchanged. It uses a lambda function to apply the conversion formula ?

import pandas as pd

# Create DataFrame with temperature data
df = pd.DataFrame({
    'Id': [1, 2, 3, 4, 5],
    'Celsius': [37.5, 36, 40, 38.5, 39]
})

print("Original DataFrame:")
print(df)

# Convert Celsius to Fahrenheit using assign()
df_converted = df.assign(Fahrenheit=lambda x: (9/5) * x['Celsius'] + 32)
print("\nDataFrame with Fahrenheit column:")
print(df_converted)
Original DataFrame:
   Id  Celsius
0   1     37.5
1   2     36.0
2   3     40.0
3   4     38.5
4   5     39.0

DataFrame with Fahrenheit column:
   Id  Celsius  Fahrenheit
0   1     37.5        99.5
1   2     36.0        96.8
2   3     40.0       104.0
3   4     38.5       101.3
4   5     39.0       102.2

Using apply() Method

The apply() method directly modifies the existing DataFrame by adding a new column. The axis=1 parameter applies the function row-wise ?

import pandas as pd

# Create DataFrame with temperature data
df = pd.DataFrame({
    'Id': [1, 2, 3, 4, 5],
    'Celsius': [37.5, 36, 40, 38.5, 39]
})

print("Original DataFrame:")
print(df)

# Convert Celsius to Fahrenheit using apply()
df['Fahrenheit'] = df.apply(lambda x: (9/5) * x['Celsius'] + 32, axis=1)
print("\nDataFrame after adding Fahrenheit column:")
print(df)
Original DataFrame:
   Id  Celsius
0   1     37.5
1   2     36.0
2   3     40.0
3   4     38.5
4   5     39.0

DataFrame after adding Fahrenheit column:
   Id  Celsius  Fahrenheit
0   1     37.5        99.5
1   2     36.0        96.8
2   3     40.0       104.0
3   4     38.5       101.3
4   5     39.0       102.2

Comparison

Method Modifies Original Best For
assign() No (returns new DataFrame) Functional programming style
apply() Yes (adds column directly) In-place modifications

Conclusion

Both methods effectively convert Celsius to Fahrenheit using the formula (9/5) × Celsius + 32. Use assign() for immutable operations or apply() for direct DataFrame modification.

Updated on: 2026-03-25T16:33:25+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements