繁体   English   中英

如何在按数据透视表Pandas分组的列上添加条件

[英]How to add conditions to columns at grouped by pivot table Pandas

我使用了pandas包中的group by和pivot表来创建下表:

输入:

q4 = q1[['category','Month']].groupby(['category','Month']).Month.agg({'Count':'count'}).reset_index()
q4 = pd.DataFrame(q4.pivot(index='category',columns='Month').reset_index())

然后输出:

category                            Count
Month                       6       7       8
0   adult-classes           29.0    109.0   162.0
1   air-pollution           27.0    43.0    13.0
2   babies-and-toddlers     4.0     51.0    2.0
3   bicycle                 210.0   96.0    23.0
4   building                NaN     17.0    NaN
5   buildings-maintenance   23.0    12.0    NaN
6   catering                1351.0  4881.0  1040.0
7   childcare               9.0     NaN     NaN
8   city-planning           105.0   81.0    23.0
9   city-services           2461.0  2130.0  1204.0
10  city-taxes              1.0     4.0     42.0

我正在尝试为月份添加条件,但我遇到的问题是,旋转后无法访问列

如何仅显示6 <7 <8的行?

要弄平多索引,可以对列进行重命名(请查看此答案 )。

q4.columns = [''.join([str(c) for c in col]).strip() for col in q4.columns.values]

删除NaN

q4.fillna(0, inplace=True)

要根据您的限制进行选择:

result = q4[(q4['Count6'] < q['Count7']) & (q4['Count7'] < q4['Count8'])]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM