Python 熊猫列表中的词频

Python 熊猫列表中的词频,python,python-3.x,pandas,nlp,spacy,Python,Python 3.x,Pandas,Nlp,Spacy,我有一列标记化、柠檬化的文本。我试图创建一个词频矩阵,这样我就可以继续进行降维了 我一直遇到一个错误,Python需要一个字符串,但得到了一个列表。 TypeError:序列项0:预期的str实例,找到列表 我试过几种方法,但每次都会出错。我不知道如何解释一份清单 以下是我尝试过的几种方法: 选项1: from collections import Counter df['new_col'] = Counter() for token in df['col']: counts[token

我有一列标记化、柠檬化的文本。我试图创建一个词频矩阵,这样我就可以继续进行降维了

我一直遇到一个错误,Python需要一个字符串,但得到了一个列表。
TypeError:序列项0:预期的str实例,找到列表

我试过几种方法,但每次都会出错。我不知道如何解释一份清单

以下是我尝试过的几种方法:

选项1:

from collections import Counter
df['new_col'] = Counter()
for token in df['col']:
    counts[token.orth_] += 1
Counter(' '.join(df['col']).split()).most_common()
pd.Series(values = ','.join([(i) for i in df['col']]).lower().split()).value_counts()[:]
此生成的
ValueError:值的长度与索引的长度不匹配

选项2:

from collections import Counter
df['new_col'] = Counter()
for token in df['col']:
    counts[token.orth_] += 1
Counter(' '.join(df['col']).split()).most_common()
pd.Series(values = ','.join([(i) for i in df['col']]).lower().split()).value_counts()[:]
其中生成:
TypeError:序列项0:预期的str实例,找到的列表

选项3:

from collections import Counter
df['new_col'] = Counter()
for token in df['col']:
    counts[token.orth_] += 1
Counter(' '.join(df['col']).split()).most_common()
pd.Series(values = ','.join([(i) for i in df['col']]).lower().split()).value_counts()[:]
它再次生成:
TypeError:sequence项0:预期的str实例,找到的列表

编辑:示例数据:

col
[indicate, after, each, action, step, .]
[during, september, and, october, please, refrain]
[the, work, will, be, ongoing, throughout, the]
[professional, development, session, will, be]
简单的回答 根据您告诉我们的,9dogs提到的最佳解决方案是使用scikit learn的
CountVectorizer
。我在这里对数据的格式做了一些假设,但下面是一个
doc x token
dataframe,其中的值是文档中token的计数。它假定
df['col']
是一个系列,其中的值是列表

>>> from sklearn.feature_extraction.text import CountVectorizer
>>> cv = CountVectorizer(analyzer=lambda x: x)
>>> counted_values = cv.fit_transform(df['col']).toarray()
>>> df = pd.DataFrame(counted_values, columns=cv.get_feature_names())
>>> df.iloc[0:5, 0:5]
   .  action  after  and  be
0  1       1      1    0   0
1  0       0      0    1   0
2  0       0      0    0   1
3  0       0      0    0   1
CountVectorizer
可以为您标记,并且默认情况下会标记,因此我们将一个identity lambda函数传递给
analyzer
参数,告诉它我们的文档已预标记

次优答案 我不建议这样做,但我认为如果您想了解计数器的工作原理,这会很有帮助。因为您的值是一个列表,所以可以在序列的每一行上使用
。apply

>>> counted_values = df['col'].apply(lambda x: Counter(x))
>>> counted_values
0    {'.': 1, 'after': 1, 'indicate': 1, 'action': ...
1    {'during': 1, 'and': 1, 'october': 1, 'please'...
2    {'will': 1, 'ongoing': 1, 'work': 1, 'the': 2,...
3    {'development': 1, 'professional': 1, 'session...
dtype: object
所以现在你有一系列的口述,这不是很有帮助。您可以通过以下方式将其转换为类似于上面的数据帧:

>>> suboptimal_df = pd.DataFrame(counted_values.tolist())
>>> suboptimal_df.iloc[0:5, 0:5]
     .  action  after  and   be
0  1.0     1.0    1.0  NaN  NaN
1  NaN     NaN    NaN  1.0  NaN
2  NaN     NaN    NaN  NaN  1.0
3  NaN     NaN    NaN  NaN  1.0

我不建议这样做,因为
apply
速度很慢,加上我们将列表存储为系列值已经有点愚蠢,dict也同样愚蠢。数据框架作为数字或字符串值的结构化容器(想想电子表格)做得最好,而不是不同的容器类型

如果您希望解决问题,请通过示例提供可再现的错误。现在,你正在要求社区付出努力,试图以某种方式对导致错误的数据帧进行反向工程。你能把
df['col']
@Bharath添加一个示例吗sample@LMGagne你已经完成了工作的一部分,但考虑使用,特别是如果你的词汇量很大。你能回顾一下现有的答案,如果他们回答了你的问题,你可以批准他们,或者进一步澄清你需要什么吗?非常感谢。