我只想让Pandas DataFrame中的行符合以下条件:
1)用户应该与超过X个项目进行交互 2)项目应该与超过Y个用户进行交互
当满足第二个条件时,在应用这两个条件后,对于某些用户,第一个条件失败。
groupById = df.groupby(['id']).count()
remaining = groupById[groupById.itemId > X]
df2 = df.loc[df.id.isin(remaining.index)]
groupByItem = df2.groupby(['id']).count()
remainingIt = groupByItem[groupByItem.id > Y]
final = df[df.id.isin(remaining.index) & df.itemId.isin(remainingIt.index)]
我无法理解这个递归问题。任何人吗?
答案 0 :(得分:1)
问题是您在删除没有超过X次交互的用户后对项目进行分组。您首先需要在两个条件下独立检查,然后才能合并结果。
import pandas as pd
#set threshold X and Y
X=1
Y=2
#fill dataframe with some users and items
users=pd.Series(['U1','U1','U1','U2'])
items=pd.Series(['Y1','Y2','Y3','Y1'])
frame=pd.DataFrame()
frame['user'] = users.values
frame['item'] = items.values
user item
0 U1 Y1
1 U1 Y2
2 U1 Y3
3 U2 Y1
#groupby item and user
groupByItem=frame.groupby('item').count().reset_index()
groupByUser=frame.groupby('user').count().reset_index()
item user
0 Y1 2
1 Y2 1
2 Y3 1
user item
0 U1 3
1 U2 1
#filter both on condition
filteredItems=groupByItem.loc[groupByItem['user']>X]
filteredUsers=groupByUser.loc[groupByUser['item']>Y]
#only take records where both user and items appear in filtered list
print(frame[frame['user'].isin(filteredUsers.user) & frame['item'].isin(filteredItems.item)])
user item
0 U1 Y1
希望这有帮助