我有一个数据框:
First name Last name Height weight unit
0 Merna Imel 185 89 kg
1 Taren Kuehn 189 123 lbs
2 Ginette Schutte 199 67 kg
3 Natasha Kibble 180 121 lbs
4 Lucrecia Berube 191 68 kg
5 Twana Bonebrake 156 138 lbs
6 Eugena Felberbaum 165 73 kg
7 Gussie Eddington 169 114 lbs
8 Siobhan Krupp 150 56 kg
9 Delcie Jiron 150 110 lbs
10 Allena Sandusky 166 87 kg
11 Dylan Verrill 166 174 lbs
12 Ambrose Pasillas 186 85 kg
13 Nannette Lehrer 195 207 lbs
14 Jenifer Mcgarrah 167 94 kg
15 Tarsha Jarnigan 162 189 lbs
16 Helen Macgregor 188 101 kg
17 Kara Belfiore 179 167 lbs
18 Harvey Quesinberry 168 74 kg
我要更改它。因此,我需要所有具有“磅”的单位通过功能“磅/2.2046”将“重量”更改为公斤。然后删除“身高”列,然后创建一个新的“ BMI”列,其中BMI使用公式“ weight / height ^ 2”来计算。
请帮助
答案 0 :(得分:1)
将DataFrame.loc
与掩码一起用于比较lbs
和常数的多个值,对于BMI
除列,并使用**
进行平方:
df.loc[df['unit'].eq('lbs'), 'weight'] *= 0.454
df['BMI'] = (df.weight/df.Height)**2
print (df)
First name Last name Height weight unit BMI
0 Merna Imel 185 89.000 kg 0.231439
1 Taren Kuehn 189 55.842 lbs 0.087297
2 Ginette Schutte 199 67.000 kg 0.113356
3 Natasha Kibble 180 54.934 lbs 0.093140
4 Lucrecia Berube 191 68.000 kg 0.126751
5 Twana Bonebrake 156 62.652 lbs 0.161295
6 Eugena Felberbaum 165 73.000 kg 0.195739
7 Gussie Eddington 169 51.756 lbs 0.093788
8 Siobhan Krupp 150 56.000 kg 0.139378
9 Delcie Jiron 150 49.940 lbs 0.110845
10 Allena Sandusky 166 87.000 kg 0.274677
11 Dylan Verrill 166 78.996 lbs 0.226461
12 Ambrose Pasillas 186 85.000 kg 0.208839
13 Nannette Lehrer 195 93.978 lbs 0.232265
14 Jenifer Mcgarrah 167 94.000 kg 0.316827
15 Tarsha Jarnigan 162 85.806 lbs 0.280547
16 Helen Macgregor 188 101.000 kg 0.288620
17 Kara Belfiore 179 75.818 lbs 0.179407
18 Harvey Quesinberry 168 74.000 kg 0.194019