pandas 数据帧来计算矩阵 [英] Pandas dataframe to count matrix
本文介绍了 pandas 数据帧来计算矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这一点很明显,但我找不到一个简单的解决方案。
This must be obvious, but I couldn't find an easy solution.
我有这样的大熊猫数据框:
I have pandas DataFrame like this:
actual | predicted
------ + ---------
Apple | Apple
Apple | Apple
Apple | Banana
Banana | Orange
Orange | Apple
我想要:
I want this:
| Apple | Banana | Orange
------ + ------- + ------- + -------
Apple | 2 | 1 | 0
Banana | 0 | 0 | 1
Orange | 1 | 0 | 0
推荐答案
您可以使用 groupby
与汇总 size code>
和 unstack
MultiIndex
:
You can use groupby
with aggregating size
and unstack
MultiIndex
:
df = df.groupby(['actual','predicted']).size().unstack(fill_value=0)
print (df)
predicted Apple Banana Orange
actual
Apple 2 1 0
Banana 0 0 1
Orange 1 0 0
另一个解决方案是 crosstab
:
Another solution with crosstab
:
df = pd.crosstab(df.actual, df.predicted)
print (df)
predicted Apple Banana Orange
actual
Apple 2 1 0
Banana 0 0 1
Orange 1 0 0
这篇关于 pandas 数据帧来计算矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文