python - 使用 python pandas 将字符串数据汇总为百分比
问题描述
给定以下数据:
x = "foo"
y = "bar"
z = "baz"
t1 = "fior"
t2 = "ropir"
d1 = pd.DataFrame(dict(type=[t1] * 4 + [t2] * 4, response=[x, y, x, x, x, z, z, z],))
看起来像
type response
0 fior foo
1 fior bar
2 fior foo
3 fior foo
4 ropir foo
5 ropir baz
6 ropir baz
7 ropir baz
怎么能概括为
d2 = pd.DataFrame(
dict(
type=[t1] * 3 + [t2] * 3,
response=[x, y, z] * 2,
percentage=[0.75, 0.25, 0, 0.25, 0, 0.75],
)
)
这是作为
type response percentage
0 fior foo 0.75
1 fior bar 0.25
2 fior baz 0.00
3 ropir foo 0.25
4 ropir bar 0.00
5 ropir baz 0.75
解决方案
您可以使用groupby
和 normalized value_counts
,然后rename
是 Series ,使用每列中的from值reindex
创建所有可能的类型响应,然后 finally 。MultiIndex.from_product
unique
reset_index
d1.groupby('type')['response'].value_counts(normalize=True)\
.rename('percentage')\
.reindex(pd.MultiIndex.from_product([d1['type'].unique(), d1['response'].unique()],
names=['type','response']),
fill_value=0)\
.reset_index()
type response percentage
0 fior foo 0.75
1 fior bar 0.25
2 fior baz 0.00
3 ropir foo 0.25
4 ropir bar 0.00
5 ropir baz 0.75
推荐阅读
- codeigniter - 如何让 Codeigniter 在表格视图中显示所有条目而不限制为 10 行数据?
- xpath - eXist-db - XQuery - Lucene - controlling output in KWIC function with callback parameter
- ruby - 在纯红宝石中将 camelCase 转换为破折号(连字符)
- python - mypy 和 attrs:错误类型检查子类列表
- c++ - QT OpenSSL AES 256 CBC 加密程序在尝试写入文件时崩溃
- javascript - How to create a slider in a stack layout
- c# - C# do..while 循环列表
- vue.js - 如何在Vue中设置默认选择
- wpf - 如何在 WPF 中折叠星形网格列?
- node.js - 错误:节点套接字仅在我的机器上挂起