gpt4 book ai didi

python - 数据框组合

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:32 25 4
gpt4 key购买 nike

我正在研究一个大型多索引数据框,其中包含多个索引,例如segmentperiodclassification 以及包含结果的几列,例如结果1结果2。 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

我正在对所有(ABC)运行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 中?

最佳答案

使用上面的示例,仅 consolidated_df.ix['A'] = result_calc 怎么样?

(与 consolidated_df.ix['A', :, :] = result_calc 相同)

print(consolidated_df)

Results1 Results2
Segment Period Classification
A 1 x 1.290466 0.228978
y -0.276959 0.735192
2 x 0.757339 -0.787502
y -0.609848 0.805773
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

关于python - 数据框组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40474997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com