我试图计算pandas DataFrame列中元素的频率.
一些玩具数据:
d = pd.DataFrame({'letters':[['a', 'b', 'c'], np.nan, ['a', 'e', 'd', 'c'], ['a', 'e', 'c']]})
Run Code Online (Sandbox Code Playgroud)
我能想到的是遍历行并向字典添加值:
letter_count = {}
for i in range(len(d)):
if d.iloc[i, ]['letters'] is np.nan:
continue
else:
for letter in d.iloc[i, ]['letters']:
letter_count[letter] = letter_count.get(letter, 0) + 1
Run Code Online (Sandbox Code Playgroud)
这对我有用,除非它的数据集很大,因此速度不是很快.我假设通过避免明确的for循环可能有所帮助,但我无法想出更多'pandasian'方法来做到这一点.
任何帮助表示赞赏.
使用chain.from_iterable扁平化的列表,然后Counter指望他们:
from itertools import chain
from collections import Counter
pd.Series(Counter(chain.from_iterable(d.letters.dropna())))
a 3
b 1
c 3
e 2
d 1
dtype: int64
Run Code Online (Sandbox Code Playgroud)
或者,value_counts用于计数步骤:
pd.Series(list(chain.from_iterable(d.letters.dropna()))).value_counts()
a 3
c 3
e 2
b 1
d 1
dtype: int64
Run Code Online (Sandbox Code Playgroud)
或者,np.unique也非常高效:
u, c = np.unique(list(chain.from_iterable(d.letters.dropna())), return_counts=True)
pd.Series(dict(zip(u, c)))
a 3
b 1
c 3
d 1
e 2
dtype: int64
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |