python - 如何通过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 .
.
像这样!
我应该在这个鳕鱼中改变什么才能得到这个结果?
解决方案
为什么不只是sort_index
pd.concat([DayFreq ,HourFreq ,TypeFreq],keys=[0,1,2]).sort_index(level=0)
推荐阅读
- c++ - //初始化一个新的由p指向的INTSTK,它最多可以存储m个整数
- sql - 如何在 Google BigQuery SQL 中做 LAG & LEAD?
- prestashop-1.7 - prestashop1.7 下拉列表中的 ps_mainmeu 不起作用
- c++ - 错误:'Foam::Field 类型的绑定引用
&' 到 'const Foam::Field ' 丢弃限定符 - python - Python 面向对象编程:组合
- flutter - 使用颤振创建网格
- database - 将数据过滤器设置为包含数字 > 的字符串字段,而不是包含数字的变量
- python - 折扣计算器有问题
- python - 三重 sql 内连接或使用 python 使用 mongodb 库获取相同的数据?
- python-3.x - Python API 从 NOAA 返回值