丛系列中的 pandas 计数频率 [英] Pandas count frequencies within str series
本文介绍了丛系列中的 pandas 计数频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,给出了系列
s = pd.Series(['abc,def,ghi','ghi,abc'])
我想获得
abc:2
def:1
ghi:2
。如何获得这个?
编辑:解决方案应该有效地处理5000万行的大系列。
解决方案
另一个熊猫解决方案与 str.split
, sum
和 value_counts
:
print pd.Series(s.str.split(',')。sum())。value_counts()
abc 2
ghi 2
def 1
dtype:int64
编辑: / p>
更有效的方法:
将大熊猫导入为pd
s = pd.Series(['abc,def,ghi','ghi,abc'])
s = pd.concat([s] * 10000).reset_index(drop = True)
在[17]中:%timeit pd.Series(s.str.split(',')。sum())。value_counts()
1循环,最好的3 :3.1s per loop
在[18]中:%timeit s.str.split(',',expand = True).stack()。value_counts()
10循环,最好3:46.2 ms每个循环
在[19]中:%timeit pd.DataFrame([x.split(',')for s in s.tolist()])。stack()。 value_counts()
10循环,最好3:22.2 ms每循环
在[20]中:%timeit pd.Series([x.split(',' )for x in s.tolist()] for item in sublist])。value_counts()
100循环,最好3:16.6 ms每循环
Given a Pandas Series of type str, I want to get the frequencies of the result returned by str.split.
For example, given the Series
s = pd.Series(['abc,def,ghi','ghi,abc'])
I would like to get
abc: 2
def: 1
ghi: 2
as a result. How can I get this?
Edit: The solution should efficiently work with a large Series of 50 million rows.
解决方案
Another pandas solution with str.split
, sum
and value_counts
:
print pd.Series(s.str.split(',').sum()).value_counts()
abc 2
ghi 2
def 1
dtype: int64
EDIT:
More efficent methods:
import pandas as pd
s = pd.Series(['abc,def,ghi','ghi,abc'])
s = pd.concat([s]*10000).reset_index(drop=True)
In [17]: %timeit pd.Series(s.str.split(',').sum()).value_counts()
1 loops, best of 3: 3.1 s per loop
In [18]: %timeit s.str.split(',', expand=True).stack().value_counts()
10 loops, best of 3: 46.2 ms per loop
In [19]: %timeit pd.DataFrame([ x.split(',') for x in s.tolist() ]).stack().value_counts()
10 loops, best of 3: 22.2 ms per loop
In [20]: %timeit pd.Series([item for sublist in [ x.split(',') for x in s.tolist() ] for item in sublist]).value_counts()
100 loops, best of 3: 16.6 ms per loop
这篇关于丛系列中的 pandas 计数频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文