我有一列字串,其中每一行都是字串串列。我想完整地計算列的元素,而不僅僅是用 pandas 中的 value.counts() 獲得的行。我想應用 Collections 模塊中的 Counter() ,但它只在串列上運行。我在 DataFrame 中的列如下所示:
[['FollowFriday', 'Awesome'],
['Covid_19', 'corona', 'Notagain'],
['Awesome'],
['FollowFriday', 'Awesome'],
[],
['corona', Notagain],
....]
我想得到計數,例如
[('FollowFriday', 2),
('Awesome', 3),
('Corona', 2),
('Covid19'),
('Notagain', 2),
.....]
我使用的基本命令是:
from collection import Counter
Counter(df['column'])
要么
from collections import Counter
Counter(" ".join(df['column']).split()).most_common()
任何幫助將不勝感激!
uj5u.com熱心網友回復:
IIUC,您與 pandas 的比較只是為了說明您的目標并且您想使用串列?
您可以使用:
l = [['FollowFriday', 'Awesome'],
['Covid_19', 'corona', 'Notagain'],
['Awesome'],
['FollowFriday', 'Awesome'],
[],
['corona', 'Notagain'],
]
from collections import Counter
from itertools import chain
out = Counter(chain.from_iterable(l))
或者如果您有一系列串列,請使用explode:
out = Counter(df['column'].explode())
# OR
out = df['column'].explode().value_counts()
輸出:
Counter({'FollowFriday': 2,
'Awesome': 3,
'Covid_19': 1,
'corona': 2,
'Notagain': 2})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/445140.html
