简体   繁体   English

使用索引元组值作为数据帧的行和列名称将Pandas groupby.groups结果转换为数据帧

[英]Converting Pandas groupby.groups result into dataframe, using index tuple value as row and columns name of dataframe

the resuts of my groupby.groups return : 我的groupby.groups的结果返回:

{(2014, 36): [2], (2014, 41): [3, 4], (2013, 10): [0], (2014, 48): [5], (2014, 37): [1]}

i want to convert it into a dataframe that will looks like : 我想将其转换为如下所示的数据框:

      2013 2014
10    1    0
36    0    1
37    0    1
41    0    2
48    0    1 

-- adds -- here is my workflow to the groupby.groups results : -添加-这是我的工作流程到groupby.groups结果中:

def tr_epoch(epoch):
       y,wn,dn = epoch.isocalendar()
       return y, wn

d = [1362826800, 1410260400, 1409828400, 1412766000, 1412769600, 1417262400 ] 
l = map(lambda x:  tr_epoch(datetime.datetime.fromtimestamp(x)), d)
df = pd.DataFrame(l, columns=['year','week_idx'])
res = df.groupby(['year','week_idx']).groups

-- adds -- in pythonic way, using iteration, i will do : -以pythonic方式添加-使用迭代,我会做:

def  to_dict(k,v):
    yr, wk = k
    return {'week': wk, yr: len(v)}

data =  map(lambda(k,v): to_dict(k,v), res.iteritems())
df = pd.DataFrame.from_records(data, index='week').fillna(0).sort()

But i am sure, there is a pandas way to do. 但我敢肯定,有一种熊猫方法。

So you want to calculate the size of each group? 因此,您要计算每个组的大小? Then you can do: 然后,您可以执行以下操作:

In [31]: df.groupby(['year','week_idx']).size()
Out[31]:
year  week_idx
2013  10          1
2014  36          1
      37          1
      41          2
      48          1
dtype: int64

To reshape this to the expected output, we can now use unstack to move the 'year' index level from the rows to the columns (and the use fillna to get 0's): 为了将其重塑为预期的输出,我们现在可以使用unstack将“年”索引级别从行移动到列(并使用fillna来获取0):

In [33]: df.groupby(['year','week_idx']).size().unstack(0).fillna(0)
Out[33]:
year      2013  2014
week_idx
10           1     0
36           0     1
37           0     1
41           0     2
48           0     1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM