[英]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.