首页 > 解决方案 > 如何通过for循环将多索引系列附加到数据帧

问题描述

我必须获取每个 CUS_ID 的 DAY、HOUR 和 Type 频率。在我的代码中,我只得到了最后一个 CUS_ID 的频率。我不知道如何获得所有这些。我已经尝试过 pd.append(ignore_index=True),但它使我的 df 杂乱无章。

此图像是编译结果。在此处输入图像描述 CUS_ID 有 70 个,最后一个是 2449。

first_df 包含此代码中的所有原始数据。

DayFreq = first_df.groupby(['CUS_ID', 'DAY']).size()
HourFreq = first_df.groupby(['CUS_ID', 'TIME_HOUR']).size()
TypeFreq = first_df.groupby(['CUS_ID', 'ACT_NM']).size()

allCUS = first_df.groupby('CUS_ID').size() 
df_con = pd.DataFrame()
idx = 0

for idx in allCUS.index:
       df_con = pd.concat([DayFreq.loc[idx, :], HourFreq.loc[idx, :], TypeFreq.loc[idx, :]], axis = 0, join = 'outer') 
       idx = idx + 1

我想要得到的是

CUS_ID DAY
2      FRI      925
        .
        .
        .
CUS_ID FRI      599
2449    .
        .

像这样!

我应该在这个鳕鱼中改变什么才能得到这个结果?

标签: pythonpandasdataframeseries

解决方案


为什么不只是sort_index

pd.concat([DayFreq ,HourFreq ,TypeFreq],keys=[0,1,2]).sort_index(level=0) 

推荐阅读