微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何根据给定的列唯一值对 csv 文件进行字数统计?

如何解决如何根据给定的列唯一值对 csv 文件进行字数统计?

我有一个 csv 文件,其中包含我想根据“类型”字段值进行字数统计的数据。以下是我的 csv 文件中的数据:

type  |  text
type1,random series of text
type1,random series of text
type2,random series of text
type3,random series of text

对于每种类型,我想进行字数统计,然后根据类型列中的值将结果输出到 csv 文件问题是文本域中可以有多个词 属于另一种类型。例如,'random' 多次出现在 type1、type2 和 type3 中。我想找到一种按类型统计总字数的方法

例如,基于上面的 csv 文件,我想要的输出如下所示:

word    |count  | type

random,3,type1
series,type1
of,type1
text,type1
random,2,type2
series,type2
of,type2
text,type2
random,type3
series,type3
of,type3
text,type3

在我的脑海中,我想将数据放入一个数据框中,然后将不同的类型值放入一个列表中,根据类型值列表循环遍历 csv 文件中的记录,然后将字数附加到一个新的.csv 文件。我已经启动了一个脚本,但在如何完成此代码方面遇到了麻烦。

这是我的脚本:

import pandas as pd
in_file = r"data.csv"


df = pd.read_csv(in_file,encoding='latin-1' )

#Create a list of all the unique type values
type_list = df['type'].unique().tolist()


df=pd.DataFrame()

# Loop over type list and do a word count on the text column
for x in type_list:
    df.append({'word': df["text"].str.split("\s",expand=True).stack(),'count':df["NOTETEXT"].str.split("\s",expand=True).value_counts(),'type':x},ignore_index=False)

# Output to csv file
df.to_csv(r'outputfile.csv')

任何想法或建议都适用,因为我是 Python 新手。

解决方法

试试 explode + value_counts

import pandas as pd

df = pd.DataFrame({
    'type': {0: 'type1',1: 'type1',2: 'type1',3: 'type2',4: 'type2',5: 'type3',6: 'type3'},'text': {0: 'random series of text',1: 'random series of text',2: 'random series of text',3: 'random series of text',4: 'random series of text',5: 'random series of text',6: 'random series of text'}
})

df['text'] = df['text'].str.split()

df = df.explode('text').value_counts().reset_index(name='count')

print(df)

df

     type    text  count
0   type1      of      3
1   type1  random      3
2   type1  series      3
3   type1    text      3
4   type2      of      2
5   type2  random      2
6   type2  series      2
7   type2    text      2
8   type3      of      2
9   type3  random      2
10  type3  series      2
11  type3    text      2

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?