Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เขียนโปรแกรม Python Pandas แปลงคอลัมน์ Celsius ใน DataFrame เป็น Fahrenheit


ผลลัพธ์สำหรับการแปลง Celsius เป็น Fahrenheit คือ

   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

เพื่อแก้ปัญหานี้ เราจะทำตามวิธีด้านล่าง −

Solution 1

  • กำหนด DataFrame พร้อมคอลัมน์ 'Id' และ 'Celsius'

  • ใช้ df.assign พร้อม Lambda Function แปลง Celsius ด้วยสูตร (9/5)*df['Celsius']+32 และ Assign ให้ Fahrenheit คือ ด้านล่าง −

df.assign(Fahrenheit = lambda x: (9/5)*x['Celsius']+32)

ตัวอย่าง

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)

ผลลัพธ์

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

Solution 2

  • กำหนด DataFrame พร้อมคอลัมน์ 'Id' และ 'Celsius'

  • ใช้ df.apply พร้อม Lambda Function แปลง Celsius ด้วยสูตร (9/5)*df['Celsius']+32 และเก็บไว้ใน df['Fahrenheit'] คือ ด้านล่าง

df['Fahrenheit'] = df.apply(lambda x: (9/5)*x['Celsius']+32, axis=1)

ตัวอย่าง

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)

ผลลัพธ์

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