我是一個python.new,在以下問題中需要一些幫助:
我有一個這樣的資料框。
東風:
| 指數 | 高度 | 單元 |
|---|---|---|
| 0 | 181.5 | 厘米 |
| 1 | 72.5 | 英寸 |
| 2 | 168.0 | 厘米 |
| 3 | 鈉 | 鈉 |
| .. | .. | .. |
...2000 行
df = pd.DataFrame(data=[[181.5,'cm'],
[72.5,'inches'],
[168.0,'cm'],
['NaN','NaN']],
columns = ['height','unit'],
index=[1,2,3,4])
我想將 統一unit為“cm”,并對 進行相應的更改height,并保留 'NaN'。
uj5u.com熱心網友回復:
使用字典映射轉換因子并使用索引來更新值/單位:
# ensure real NaNs:
df = df.replace('NaN', np.nan)
# set up dictionary of conversion factors
d = {'cm': 1, 'inches': 2.54}
# map converted heights
df['height'] = df['height'].mul(df['unit'].map(d))
# update units
df.loc[df['unit'].isin(d), 'unit'] = 'cm'
輸出:
height unit
1 181.50 cm
2 184.15 cm
3 168.00 cm
4 NaN NaN
處理未知單位
如果您想處理單位未知的值并保持不變,請使用map(lambda x: d.get(x, 1))而不是map
uj5u.com熱心網友回復:
使用蒙版從此解決方案調整:
mask = (df['unit'] == 'inches')
df_inches = df[mask]
df.loc[mask, 'height'] = df_inches['height'] * 2.54
df.loc[mask, 'unit'] = 'cm'
print(df)
輸出:
height unit
1 181.5 cm
2 184.15 cm
3 168.0 cm
4 NaN NaN
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/447957.html
