遍历Pandas Groupby和合并DataFrames [英] Iterating through Pandas Groupby and Merging DataFrames

查看:114
本文介绍了遍历Pandas Groupby和合并DataFrames的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎应该很简单,但是却让我感到难过.真的很喜欢能够在groupby操作的各个组之间进行迭代,并且我从groupby中获得了想要的结果,但是我无法将最终结果合并到一个数据帧中.所以从本质上讲,我有下面的代码可以捕获列表中的数据帧,但是我不知道如何遍历一个数据帧列表来制作一个数据帧:

This seems like it should be straightforward but is stumping me. Really love being able to iterate through the groups of a groupby operation and I am getting the result I want from the groupby but I am unable to merge the final result into one dataframe. So essentially I have the below code which can capture the dataframes in a list but I don't know how to loop through a list of dataframes to make one dataframe:

dfs = []
for name, group in df.groupby('date', sort=False):
    dfs.append(pd.DataFrame(pd.DataFrame(list(chain.from_iterable(group['values'])),
                              columns=['col']).groupby('col').size(),
                               columns=[name]).reset_index())

然后我得到以下信息(仅显示dfs [0]和dfs [1],但我最多有dfs [8]:

and I get the following (just showing dfs[0] and dfs[1] but I have up to dfs[8]:

   [   col1 col2
    0  val1 val2,
    ...
       col1 col2
    0  val1 val2]
    ...

我只想将它们全部合并到col1键上.换句话说,以下方法效果很好,但是如何在不对列表中的各个元素进行硬编码并在dfs中遍历所有元素的情况下做到这一点呢?

And I just want to merge them all on the col1 key. In other words the following works great but how do I do it without hardcoding the individual elements in the list and loop through all of them in dfs?

pd.concat([dfs[0], dfs[1]], axis=1, join='outer')

推荐答案

为什么不只是:

pd.concat(dfs, axis=1, join='outer')

这篇关于遍历Pandas Groupby和合并DataFrames的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆