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

标签 python pandas dataframe

我有一个数据帧字典,如下所示。

enter image description here

目前我想做的是替换每个数据帧的 FR 列中的值,并为每个数据帧创建一个名为 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'

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

您能让我知道如何进一步改进吗?

最佳答案

您可以使用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)

但是如果你没有字典,那么你就无法更改代码。

关于python - 替换多个值并为多个数据帧创建新列的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57263986/

相关文章:

python - 在 NumPy 数组中记录迄今为止的最小值

python - 从 pandas df 列名和值创建新列

python - pandas 数据框中不重叠的滚动窗口

python - 将数据框列与系列相乘

python - 图形工具中的顶点坐标

python - 检查列的每一行是否在范围内

python - PyQt:从对话框访问主窗口的数据?

python - 如何强制 Altair 在特定轴上对热图(矩形)进行排序?

python - 连接多个数据帧

python - 当 Min_count=1 时,Groupby 和等于 0