python - 如何制作一个包含每个单词的新数据框并使用另一列进行计数
问题描述
让我解释。我的df
样子是这样的:
id ` text c1
1 Hello world how are you people 1
2 Hello people I am fine people 1
3 Good Morning people -1
4 Good Evening -1
c1
仅包含两个值 1 或 -1
现在我想要一个这样的数据框(输出):
Word Totalcount Points PercentageOfPointAndTotalCount
hello 2 2 100
world 1 1 100
how 1 1 100
are 1 1 100
you 1 1 100
people 3 1 33.33
I 1 1 100
am 1 1 100
fine 1 1 100
Good 2 -2 -100
Morning 1 -1 -100
Evening 1 -1 -100
这里,是每个单词在列中Totalcount
出现的总次数。text
points
是c1
每个单词的总和。示例:people
单词在两行中c1
是 1,在一行中c1
是1 -1
。所以重点是 1 (2-1 = 1)。
PercentageOfPointAndTotalCount = 点数/TotalCount*100
print(df)
id comment_text target
0 59848 Hello world -1.0
1 59849 Hello world -1.0
解决方案
之后我使用取消嵌套str.split,
,我们只需要groupby
+agg
unnesting(df,['text']).groupby('text').c1.agg(['count','sum'])
Out[873]:
count sum
text
Evening 1 -1
Good 2 -2
Hello 2 2
I 1 1
Morning 1 -1
am 1 1
are 1 1
fine 1 1
how 1 1
people 4 2
world 1 1
you 1 1
def unnesting(df, explode):
idx = df.index.repeat(df[explode[0]].str.len())
df1 = pd.concat([
pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1)
df1.index = idx
return df1.join(df.drop(explode, 1), how='left')
推荐阅读
- java - 如何使用 Java 程序修改已编译的 .jar 中的类文件中的字符串?
- javascript - 将 API 和固定价格的最大标题长度设置为小数点后两位
- react-native - 分析数据未显示在 Firebase 控制台中
- kubernetes - 是否可以在 gcp 永久磁盘上编辑文件?
- azure - 在可能存在多个选项的情况下,如何创建策略以强制标记?
- java - ArrayDeque<>(int capacity) - Scanner.nextInt() == 4 和 (int) 4 有什么区别?
- python - button.when_pressed 中引用函数的返回值
- javascript - 无法使用 JSON 数据作为图表的输入在 Codeigniter 页面上显示 Morris.JS 图表
- javascript - 使用 Fetch API 调用带有 Auth Token 的 URL
- java - 有没有办法通过硒自动化在gmail中撰写邮件?