python - 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”之间的相关性。你能帮我解决以上问题吗?我不知何故错过了最后一个循环中键的使用。提前致谢!
解决方案
所有这些循环都是完全没有必要的!只需调用:
df.groupby(['Home', 'Season'])['Consumption', 'Temp'].corr()
(感谢@jezrael 的更正)
推荐阅读
- swift - 对单个属性使用多个 CodingKey
- scala - 如何在 ReactiveMongo 中使用 where 运算符?
- image-processing - 如何计算不同图像的阈值以传递给 houghlines 函数?
- powershell - 为嵌套 OU 中的 ADGroup 设置 ManagedBy
- python - 为什么 CopyData 实用程序在一段时间后停止工作?
- javascript - 无法通过 CSS 设置自定义纸张大小
- google-api - 在 Google Drives API v3 的列表操作中获取附加字段
- python - 如何用手指从图像中提取指甲?
- seo - 打开图形描述元标记在 LinkedIn 中不起作用
- powershell - 将已发送的电子邮件复制到已发送文件夹(电子邮件服务器)