私はmultiIndex DataFrameを使用していて、groupby/apply()操作をいくつか行いたいと思います。私はgroupbyをどのように組み合わせて適用するかと苦労しています。multiindex DataFramesでgroupbyを適用して適用する
私は、DataFrameの2つのインデックスの値を抽出して、それらの値を適用関数で比較したいと考えています。
apply関数がtrueの場合は、私のDataFrameの値に対してgroupby/sumを実行したいと思います。
forループを使用せずにこれを行う良い方法はありますか?ここで
# Index specifier
ix = pd.MultiIndex.from_product(
[['2015', '2016', '2017', '2018'],
['2016', '2017', '2018', '2019', '2020'],
['A', 'B', 'C']],
names=['SimulationStart', 'ProjectionPeriod', 'Group']
)
df = pd.DataFrame(np.random.randn(60,1), index= ix, columns=['Input'])
# Calculate sum over all projection periods for each simulation/group
all_periods = df.groupby(level=['SimulationStart', 'Group']).sum()
# This part of the code is not working yet
# is there a way to extract data from the indices of the DataFrame?
# Calculate sum over all projection periods for each simulation/group;
# where projection period is a maximum of one year in the future
one_year_ahead = df.groupby(level=['SimulationStart', 'Group']) \
.apply(lambda x: x['ProjectionPeriod'] - \
x['SimulationStart'] <= 1).sum()
あなたの応答をありがとうございました。これは非常に役に立ちます。インデックスのピリオドが実際に文字列形式であるため、私のコードはまだうまくいきません。 – Andreas