从python中的数据帧中计算不同的单词

2024-04-24 02:53:30 发布

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

我试着分词,然后用Python数数。你知道吗

原始数据是这样的

col_A 

happy, not happy
sad,happy
sad, happy
angry, happy
angry, sad

我试着用这个函数来计算A列中的单词

word_list= df.col_A.apply(lambda x: pd.value_counts(x.split(","))).sum(axis=0)

word_list.sort_values(ascending = False)

它会给我这样的结果

angry       2
happy       2
sad         2
 happy      2
 not happy  1
 sad        1

如何避免这些空格来返回值的实际计数?你知道吗

我想返回一个列表,比如

happy      4
sad        3
angry      2
not happy  1

Tags: lambda函数df原始数据notcol单词list
3条回答

这里有一个非常类似于@anky\u 91的解决方案:

In [96]: df.col_A.str.replace(r"\s*,\s*", ",").str.get_dummies(",").sum()
Out[96]:
angry        2
happy        4
not happy    1
sad          3
dtype: int64

让我们将meltstackstr.splitvalue_counts一起使用:

df['col_A'].str.split(r',\s?', expand=True).melt()['value'].value_counts()

或者

df['col_A'].str.split(r',\s?', expand=True).stack().value_counts()

输出:

happy        4
sad          3
angry        2
not happy    1
dtype: int64

一个班轮,不能保证效率,但它的工作:)

pd.Series([x.strip() for x in df.col_A.str.split(',').sum()]).value_counts()

输出:

happy        4
sad          3
angry        2
not happy    1

效率测试:

%timeit pd.Series([x.strip() for x in df.col_A.str.split(',').sum()]).value_counts()
1.19 ms ± 35.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit pd.Series(sum([list(map(str.strip, i.split(','))) for i in df['col_A']], [])).value_counts()
1.13 ms ± 20.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

相关问题 更多 >