首页 > 解决方案 > Python 3.x:对循环中的数据帧字典进行分析

问题描述

我有一个数据框(df),其列名是["Home", "Season", "Date", "Consumption", "Temp"]. 现在我要做的是通过“Home”、“Season”、“Temp”和“Consumption”对这些数据框进行计算。

In[56]: df['Home'].unique().tolist()
Out[56]: [1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

In[57]: df['Season'].unique().tolist()
Out[57]: ['Spring', 'Summer', 'Autumn', 'Winter']

这是到目前为止所做的事情:

series = {}
for i in df['Home'].unique().tolist():
    for j in df["Season"].unique().tolist():
        series[i, j] = df[(df["Home"] == i) & (df["Consumption"] >= 0) & (df["Season"] == j)]
        for key, value in series.items():
            value["Corr"] = value["Temp"].corr(value["Consumption"])

这是名为“Series”的数据框字典,作为循环的输出。

字典名称的图像

我对上一个循环的期望是给我一个数据帧字典,其中添加了一个新列,即“Corr”,它具有“Temp”和“Consumption”的相关值,但它为迭代中的最后一个主页提供了一个数据帧即23。

只需在字典中的所有数据框中添加名为“Corr”的第六列,这将是“Temp”和“Consumption”之间的相关性。你能帮我解决以上问题吗?我不知何故错过了最后一个循环中键的使用。提前致谢!

标签: pythonpython-3.xpandasloops

解决方案


所有这些循环都是完全没有必要的!只需调用:

df.groupby(['Home', 'Season'])['Consumption', 'Temp'].corr()

(感谢@jezrael 的更正)


推荐阅读