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

问题描述 投票:0回答:2

我需要一些技巧来进行计算。

我有一个如下所示的数据框:

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
列包含一个集合,因此计算两个连续版本之间的差异的操作应该很容易。

python pandas dataframe set
2个回答
2
投票

很难思考,但很有趣:-)我正在使用

get_dummies
,然后我们只保留每列的第一个
1
值和
sum
它们

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)

0
投票
col1=df1.important_words.str.replace('{|}|\s','').str.split(',')

col2=df1.assign(important_words=col1).groupby('text_id').important_words.transform(lambda ss:ss.cumsum().shift(fill_value=[[]]))

col3=df1.assign(col1=col1,col2=col2).apply(lambda ss: len(set(ss.col1).difference(set(ss.col2))), 1)

df1.assign(added_words=col3)


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
© www.soinside.com 2019 - 2024. All rights reserved.