【发布时间】:2017-03-21 09:01:33
【问题描述】:
我正在处理一个包含多个索引的大型 multiIndex 数据框,例如segment、period 和 classification 以及带有结果的几列,例如Results1,Results2。 DataFrame consolidated_df 应该存储我所有的计算结果:
import pandas as pd
import numpy as np
segments = ['A', 'B', 'C']
periods = [1, 2]
classification = ['x', 'y']
index_constr = pd.MultiIndex.from_product(
[segments, periods, classification],
names=['Segment', 'Period', 'Classification'])
consolidated_df = pd.DataFrame(np.nan, index=index_constr,
columns=['Results1', 'Results2'])
print(consolidated_df)
大DataFrame的结构如下:
Results1 Results2
Segment Period Classification
A 1 x NaN NaN
y NaN NaN
2 x NaN NaN
y NaN NaN
B 1 x NaN NaN
y NaN NaN
2 x NaN NaN
y NaN NaN
C 1 x NaN NaN
y NaN NaN
2 x NaN NaN
y NaN NaN
我正在对我的所有 segments(A、B 和 C)运行 for 循环来计算结果(使用单独的函数 calc_function 存储在 DataFrame 的列中。
此函数返回一个与合并的 DataFrame 具有完全相同格式的 DataFrame - 除了它一次只报告一个段(即它是合并 DataFrame 的一部分)。
示例:
index_result = pd.MultiIndex.from_product(
[['A'], periods, classification],
names=['Segment', 'Period', 'Classification'])
result_calc = pd.DataFrame(np.random.randn(4,2), index=index_result,
columns=['Results1', 'Results2'])
print(result_calc)
Results1 Results2
Segment Period Classification
A 1 x -1.568351 0.386250
y 0.679170 1.552551
2 x -1.190928 -0.765319
y 3.254929 1.436295
我尝试使用以下方法将结果 DataFrame 存储在合并的 DataFrame 中,但没有成功:
for segment in segments:
#calc_function returns a DataFrame that has the same structure as consolidated_df
consolidated_df.loc[idx[segment, :, :], :] = calc_function(segment)
有没有一种方法可以轻松地将较小的 DataFrame 集成到合并的 DataFrame 中?
【问题讨论】:
-
calc_function的所有行都相同吗?如果是这样,也许先计算它,然后merge它进入数据框 -
calc_function 返回的所有 DataFrame 的行完全相同(它们又是报告所有结果的 DataFrame 的子集)
-
我正在尝试在构建 index_result 但没有足够的字符时编辑您的示例:它应该为
[['A'], periods, classification](而不是['A', periods, classification]),因为 from_product 使用列表。 -
如果都是子集,为什么不连接所有段:
pd.concat(segments)? -
谢谢,我想这样也行!
标签: python pandas dataframe merge multi-index