python:如何计算一行的元素? [英] python: How to count the elements of a row?
本文介绍了python:如何计算一行的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有一个名为 a
的 DataFrame.我想计算每一行的元素.
For example, I have a DataFrame named a
. I want to count the element of each row.
import numpy as np
a=pd.DataFrame({'A1':['financial','game','game'],'A2':['social','food','sport'],'A3':['social','sport','game']})
输入:
A1 A2 A3
0 financial social social
1 game food sport
2 game sport game
预期:
financial food game social sport
0 1 0 0 2 0
1 0 1 1 0 1
2 0 0 2 0 1
希望得到帮助,谢谢!
推荐答案
使用 pandas.get_dummies
和 sum
:
df = pd.get_dummies(a, prefix_sep='', prefix='').sum(axis=1, level=0)
print (df)
financial game food social sport
0 1 0 0 2 0
1 0 1 1 0 1
2 0 2 0 0 1
或者 stack
与 SeriesGroupBy.value_counts
和 Series.unstack
:
df = a.stack().groupby(level=0).value_counts().unstack(fill_value=0)
print (df)
financial food game social sport
0 1 0 0 2 0
1 0 1 1 0 1
2 0 0 2 0 1
这篇关于python:如何计算一行的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文