替换多个值并为多个数据帧创建新列的优雅方式

2024-04-28 19:33:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧的dict,如下所示。你知道吗

enter image description here

目前,我正在尝试替换每个dataframe的FR列中的值,并为每个dataframe创建一个名为unit的新列

虽然我有一个如下所示的工作代码,但不确定这是否是编写它的最佳方式。你知道吗

dataFramesDict['Cho'] = dataFramesDict['Cho'].replace({'FR' : {'Fasting' : 'Cholesterol Fasting', 'Random' : 'Cholesterol Random'}})
dataFramesDict['HDL'] = dataFramesDict['HDL'].replace({'FR' : {'Fasting' : 'Plasma fasting HDL cholesterol measurement', 'Random' : 'Plasma random HDL cholesterol measurement'}})
dataFramesDict['LDL'] = dataFramesDict['LDL'].replace({'FR' : {'Fasting' : 'Plasma fasting LDL cholesterol measurement', 'Random' : 'Plasma random LDL cholesterol measurement'}})
dataFramesDict['Tri'] = dataFramesDict['Tri'].replace({'FR' : {'Fasting' : 'Plasma fasting triglyceride measurement', 'Random' : 'Plasma random triglyceride measurement'}})
dataFramesDict['Cho']['unit'] = 'ml'
dataFramesDict['HDL']['unit'] = 'ml'
dataFramesDict['LDL']['unit'] = 'ml'
dataFramesDict['Tri']['unit'] = 'ml'

请注意,每个数据帧要替换的值不同。但是,从代码中可以看出,所有数据帧的原始值都是相同的

你能告诉我如何进一步改进吗?你知道吗


Tags: 数据unitrandomfrmlreplacemeasurementhdl
1条回答
网友
1楼 · 发布于 2024-04-28 19:33:24

您可以使用for循环来添加列

for key in dataFramesDict:
    dataFramesDict[key]['unit'] = 'ml'

甚至

for df in dataFramesDict.values():
    df['unit'] = 'ml'

如果你有替换的字典,那么你也可以使用循环

replacements =  {  
    'Cho': {'FR' : {'Fasting' : 'Cholesterol Fasting', 'Random' : 'Cholesterol Random'}},
    'HDL': {'FR' : {'Fasting' : 'Plasma fasting HDL cholesterol measurement', 'Random' : 'Plasma random HDL cholesterol measurement'}},
    'LDL': {'FR' : {'Fasting' : 'Plasma fasting LDL cholesterol measurement', 'Random' : 'Plasma random LDL cholesterol measurement'}},
    'Tri': {'FR' : {'Fasting' : 'Plasma fasting triglyceride measurement', 'Random' : 'Plasma random triglyceride measurement'}},)
}

for key, value in replacements.items():
    dataFramesDict[key] = dataFramesDict[key].replace(value)

但是如果你没有字典,你就不能修改代码。你知道吗

相关问题 更多 >