gpt4 book ai didi

python - 依赖于计算 groupby 对象中两个列单元格之间差异的列

转载 作者:太空宇宙 更新时间:2023-11-04 01:53:25 25 4
gpt4 key购买 nike

我需要一些提示来进行计算。

我有一个如下所示的 DataFrame:

text_id      user     date        important_words
1 John 2018-01-01 {cat, dog, puppy}
1 John 2018-02-01 {cat, dog}
2 Anne 2018-01-01 {flower, sun}
3 John 2018-03-01 {water, blue}
3 Marie 2018-05-01 {water, blue, ocean}
3 Kate 2018-08-01 {island, sand, towel}
4 Max 2018-01-01 {hot, cold}
4 Ethan 2018-06-01 {hot, warm}
5 Marie 2019-01-01 {boo}

在给定的数据框中:

text_id是指文本的id:不同id的文本是不同的文本。 user 列是指编辑文本(添加和删除重要词)的用户的名称。 date 列指的是进行编辑的时间(请注意,对每个文本的编辑是临时排序的)。最后,important_words 列是用户编辑后出现在文本中的一组重要词。

我需要计算每个用户在页面的每个版本上添加了多少个单词。

这里的预期输出是:

text_id      user     date        important_words        added_words
1 John 2018-01-01 {cat, dog, puppy} 3
1 John 2018-02-01 {cat, dog} 0
2 Anne 2018-01-01 {flower, sun} 2
3 John 2018-03-01 {water, blue} 2
3 Marie 2018-05-01 {water, blue, ocean} 1
3 Kate 2018-08-01 {island, sand, towel} 3
4 Max 2018-01-01 {hot, cold} 2
4 Ethan 2018-06-01 {hot, warm} 1
5 Marie 2019-01-01 {boo} 1

请注意,第一次编辑文本是创建,因此添加的单词数始终是在这种情况下设置的 important_words 的大小。

任何有关计算 added_words 列的最快方法的提示都将受到高度赞赏。

注意 important_words 列包含一个集合,因此计算两个连续版本之间差异的操作应该很容易。

最佳答案

很难思考但很有趣 :-) 我正在使用 get_dummies,然后我们只保留每列的第一个 1 值并对它们进行求和

s=df.important_words.map(','.join).str.get_dummies(sep=',')
s.mask(s==0).cumsum().eq(1).sum(1)
Out[247]:
0 3
1 0
2 2
3 2
4 1
5 3
6 2
7 1
8 1
dtype: int64
df['val']=s.mask(s==0).cumsum().eq(1).sum(1)

更新

s=df.important_words.map(','.join).str.get_dummies(sep=',')
s.mask(s==0).groupby(df['text_id']).cumsum().eq(1).sum(1)

关于python - 依赖于计算 groupby 对象中两个列单元格之间差异的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57479656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com