我的数据框:
Name fav_fruit
0 justin apple
1 bieber justin apple
2 Kris Justin bieber apple
3 Kim Lee orange
4 lee kim orange
5 mary barnet orange
6 tom hawkins pears
7 Sr Tom Hawkins pears
8 Jose Hawkins pears
9 Shanita pineapple
10 Joe pineapple
df1=pd.DataFrame({'Name':['justin','bieber justin','Kris Justin bieber','Kim Lee','lee kim','mary barnet','tom hawkins','Sr Tom Hawkins','Jose Hawkins','Shanita','Joe'],
'fav_fruit':['apple'
,'apple'
,'apple'
,'orange'
,'orange'
,'orange'
,'pears'
,'pears','pears'
,'pineapple','pineapple']})
我想在fav_fruit列上的grouby之后计算Name列中的常用单词数,因此对于苹果,计数为2贾斯汀·比伯,对于橙色kim,lee和对于菠萝,计数为0
预期输出:
Name fav_fruit count
0 justin apple 2
1 bieber justin apple 2
2 Kris Justin bieber apple 2
3 Kim Lee orange 2
4 lee kim orange 2
5 mary barnet orange 2
6 tom hawkins pears 2
7 Sr Tom Hawkins pears 2
8 Jose Hawkins pears 2
9 Shanita pineapple 0
10 Joe pineapple 0
答案 0 :(得分:1)
我认为需要transform
具有自定义功能-首先创建一个大字符串连接值,转换为小写并拆分,最后使用collections.Counter
过滤所有重复值:
from collections import Counter
def f(x):
a = ' '.join(x).lower().split()
return len([k for k, v in Counter(a).items() if v != 1])
df['count'] = df.groupby('fav_fruit')['Name'].transform(f)
print (df)
Name fav_fruit count
0 justin apple 2
1 bieber justin apple 2
2 Kris Justin bieber apple 2
3 Kim Lee orange 2
4 lee kim orange 2
5 mary barnet orange 2
6 tom hawkins pears 2
7 Sr Tom Hawkins pears 2
8 Jose Hawkins pears 2
9 Shanita pineapple 0
10 Joe pineapple 0