Kết quả chuyển đổi Celsius sang Fahrenheit như sau:
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
Để giải quyết bài toán này, chúng ta sẽ làm theo các cách tiếp cận dưới đây:
Giải pháp 1
- Định nghĩa DataFrame với cột 'Id' và 'Celsius'
- Áp dụng df.assign với lambda function chuyển đổi Celsius: (9/5)*Celsius + 32, gán vào cột Fahrenheit
df.assign(Fahrenheit=lambda x: (9/5)*x['Celsius'] + 32)
Ví dụ
Hãy kiểm tra mã sau để hiểu rõ hơn:
import pandas as pd
df = pd.DataFrame({'Id': [1,2,3,4,5], 'Celsius': [37.5, 36, 40, 38.5, 39]})
print("DataFrame is:\n", df)
df = df.assign(Fahrenheit=lambda x: (9/5)*x['Celsius'] + 32)
print(df)
Đầu ra
DataFrame is: Id Celsius 0 1 37.5 1 2 36.0 2 3 40.0 3 4 38.5 4 5 39.0 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
Giải pháp 2
- Định nghĩa DataFrame với cột 'Id' và 'Celsius'
- Sử dụng df.apply với lambda function: (9/5)*x['Celsius'] + 32, axis=1, lưu vào df['Fahrenheit']
df['Fahrenheit'] = df.apply(lambda x: (9/5)*x['Celsius'] + 32, axis=1)
Ví dụ
Hãy kiểm tra mã sau để hiểu rõ hơn:
import pandas as pd
df = pd.DataFrame({'Id': [1,2,3,4,5], 'Celsius': [37.5, 36, 40, 38.5, 39]})
print("DataFrame is:\n", df)
df['Fahrenheit'] = df.apply(lambda x: (9/5)*x['Celsius'] + 32, axis=1)
print(df)
Đầu ra
DataFrame is: Id Celsius 0 1 37.5 1 2 36.0 2 3 40.0 3 4 38.5 4 5 39.0 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