如何把大Pandas列入名单

2024-10-04 01:34:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据框中当前有一行如下所示:

     bigrams                     other1     other2
[(me, you), (stack, overflow)] .................
[(me, you)]                    .................

我正试图把我的前10个大字列成一个列表,这样我就可以用它来做比较了。我试着复制并粘贴我的前10个大字到一个列表中,如下所示:

list = ['(me, you)',  .....]

这不管用。有人有什么建议吗?谢谢。你知道吗


Tags: 数据you列表stack粘贴建议listme
2条回答

您可以使用itertools.chain(展平“bigrams”列中的列表),然后使用pd.value_counts。你知道吗

df = pd.DataFrame({'bigrams': [['(a, b)', '(c, d)'], ['(a, b)'], ['(a, b)', '(e, f)']]})
df
            bigrams
0  [(a, b), (c, d)]
1          [(a, b)]
2  [(a, b), (e, f)]

pd.__version__
# '0.24.1'

from itertools import chain

n = 2 # Find the top N
pd.value_counts(list(chain.from_iterable(df['bigrams']))).index[:n].tolist()
# ['(a, b)', '(e, f)']

让我们用Counter

from collections import Counter

list(dict(Counter(df.bigrams.sum()).most_common(10)).keys())

如下所述,使用itertools.chain替换sum

from itertools import chain
l=list(chain.from_iterable(df['bigrams']))
list(dict(Counter(l).most_common(10)).keys())

相关问题 更多 >