基于另一个数据帧字典创建数据帧字典

时间:2015-11-25 16:57:41

标签: python dictionary pandas dataframe

我有一个字典可以保存DataFrames A,并使用month-year键编制索引。现在,我想创建另一个DataFrames B字典(带有cost-item键),该字典会随着时间的推移对每列进行记录(从A获取列)。

以下是一个例子:

A[0114]=
  title  cost1   cost2
0 FL     100     200
1 GA     300     400

A[0214]=
  title  cost1   cost2
0 FL     150     250
1 GA     100     300

B[cost1]=
  title  0114   0214
0 FL     100    150
1 GA     300    100

B[cost2]=
  title  0114   0214
0 FL     200    250
1 GA     400    300

这是我不成功的尝试:

cost_item=['cost1', 'cost2']
month_year_list=['0114', '0214']
for item in cost_item:
    B[item] = {}
    B[item]['title']= pd.Series(A['0114']['title'], index=A['0114'].index)
    for month_year in month_year_list:
        B[item][month_year]=pd.Series(A[month_year][item], index=A['0114'].index)

1 个答案:

答案 0 :(得分:0)

使用Panel

这很简单
for key in A:
    A[key].index = A[key].pop('title')
panel = pd.Panel(A)
B = panel.swapaxes(0,2)

技术上B也是一个小组,标题将是主轴,但你可以做到

B = {item: B[item] for item in B}
for key in B:
    B[key]['title'] = B.index

如果你真的想要一个原始结构的字典。但是,Panel似乎更合适,除非您在标题中有许多元素在A中的数据框架中不常见。

相关问题