Bon*_*ndo 3 python pandas pandas-groupby
我在为pandas中的数据帧生成统计信息时遇到了一些问题.我的数据框看起来像这样(我省略了索引):
id type
1 A
2 B
3 A
1 B
3 B
2 C
4 B
4 C
Run Code Online (Sandbox Code Playgroud)
重要的是,每个id都type分配了两个值,从上面的例子中可以看出.我想计算所有type组合出现次数(所以计算id给定type组合的唯一数量),所以我想得到这样一个数据帧:
type count
A, B 2
A, C 0
B, C 2
Run Code Online (Sandbox Code Playgroud)
我试过groupby很多方面,但是徒劳无功.我可以使用for-loop和多行代码来做这种"计数" ,但我相信必须有优雅和适当的(用python术语)解决这个问题.
提前感谢任何提示.
pd.value_counts 和 itertools.combinationsfrom itertools import combinations
pd.value_counts(
[(x, y) for _, d in df.groupby('id') for x, y in combinations(d.type, 2)]
)
(A, B) 2
(B, C) 2
dtype: int64
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
243 次 |
| 最近记录: |