我如何计算每个类别中与标签相比较的数量?
Credit Term Y
0 Excellent 3 safe
1 fair 5 risky
2 poor 3 risky
3 fair 5 risky
4 Excellent 5 safe
5 poor 3 risky
6 Excellent 5 safe
7 poor 3 risky
8 fair 3 safe
9 fair 5 safe
这是我的数据,我想计算有多少安全、优秀、贫穷和公平,以及有多少风险、优秀、贫穷和公平,比如优秀,3,安全,0,风险,等等。
data[(data['Credit']=='Excellent')&(data['Y']=='safe')].count()
data[(data['Credit']=='Excellent')&(data['Y']=='risky')].count()
或
elements,counts = np.unique(data['Credit'],return_counts = True)
我怎么做一张像这样的桌子?
safe risky
excellent 3 0
poor 0 3
fair 2 2
发布于 2020-06-28 04:21:13
使用Pandas groupby()
和unstack()
data.groupby(['Credit', 'Y']).count().unstack()
发布于 2020-06-28 04:22:08
您可以使用pivot_table:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html
In [16]: df
Out[16]:
credit term Y
0 Excellent 3 safe
1 fair 5 risky
2 poor 3 risky
3 Excellent 5 safe
4 fair 5 safe
In [17]: pd.pivot_table(df, index=['credit'], columns=['Y'], aggfunc='count')
Out[17]:
term
Y risky safe
credit
Excellent NaN 2.0
fair 1.0 1.0
poor 1.0 NaN
In [18]: pd.pivot_table(df, index=['credit'], columns=['Y'], aggfunc='count', fill_value=0)
Out[18]:
term
Y risky safe
credit
Excellent 0 2
fair 1 1
poor 1 0
https://stackoverflow.com/questions/62614967
复制相似问题