[英]Elegant way to check multiple if conditions in Dictionary
我有一個數據框字典,如下所示
dataFramesDict[sheet_name] = pd.DataFrame({'Date':['2007-05-30','2107-11-30','2207-05-20','2307-05-20'],'Value': [2.4,2.5,2.6,2.7],'Test': ['Height','Weight','SBP','DBP']})
我想做的是創建一個名為Unit
的新列,並根據Test
列添加值
這是我嘗試過的方法,但看起來並不優雅或高效。
if dataFramesDict[sheet_name]['Test'] == 'Height':
dataFramesDict[sheet_name]['unit'] == 'm'
if dataFramesDict[sheet_name]['Test'] == 'Weight':
dataFramesDict[sheet_name]['unit'] == 'kg'
if dataFramesDict[sheet_name]['Test'] == 'SBP':
dataFramesDict[sheet_name]['unit'] == 'millimeter'
if dataFramesDict[sheet_name]['Test'] == 'DBP':
dataFramesDict[sheet_name]['unit'] == 'millimeter'
請注意, sheet_name
是Excel工作表的一部分。 總共我有10多張紙,我想閱讀每張紙並檢查每張紙中的測試值,並根據“ Test
列分配單位值
我希望我的輸出如下所示
將map
與dict
使用
例如:
d = {'Height':"m",'Weight': "kg",'SBP':'mm','DBP':'mm'}
dataFramesDict = pd.DataFrame({'Date':['2007-05-30','2107-11-30','2207-05-20','2307-05-20'],'Value': [2.4,2.5,2.6,2.7],'Test': ['Height','Weight','SBP','DBP']})
dataFramesDict["Unit"] = dataFramesDict["Test"].map(d)
print(dataFramesDict)
輸出:
Date Test Value Unit
0 2007-05-30 Height 2.4 m
1 2107-11-30 Weight 2.5 kg
2 2207-05-20 SBP 2.6 mm
3 2307-05-20 DBP 2.7 mm
使用熊貓替換
df['unit'] = df.Test.replace({'Height':"m",'Weight': "kg",'SBP':'mm','DBP':'mm'})
請嘗試以下代碼。 希望能幫助到你:
unitDict = {'Height':'m', 'Weight': 'Kg', 'SBP':'millimeter', 'DBP':'millimeter'}
def checkUnit(data):
if unitDict[data] is not None:
return unitDict[data]
df['Unit']=list(map(checkUnit, df['Test']))
print(df)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.