Python 查找一列中的公共值与另一列中的不同值
我有一个像Python 查找一列中的公共值与另一列中的不同值,python,pandas,Python,Pandas,我有一个像 event cust et1 satya et1 papu et1 abc et1 satya et1 def et2 papu et2 satya et2 panda et3 normal et3 panda et3 satya et3 fgh 现在我需要找到所有3种类型的事件中都存在的“cust” event cust et1 satya et1 satya 不要担心不一致(重复
event cust
et1 satya
et1 papu
et1 abc
et1 satya
et1 def
et2 papu
et2 satya
et2 panda
et3 normal
et3 panda
et3 satya
et3 fgh
现在我需要找到所有3种类型的事件中都存在的“cust”
event cust
et1 satya
et1 satya
不要担心不一致(重复项可以删除)。
为此,我的方法是
x = df[df['event'] == 'et1']
y = df[df['event'] == 'et2']
z = df[df['event'] == 'et3']
df_common = x[x['cust'].isin(y[y['cust'].isin(z.cust)]['cust'])]
但这在这种情况下并不合适,因为数据帧的大小非常大,我必须为一些50-100多个事件找到通用的cust
请推荐一些熊猫/更多的蟒蛇方式。提前谢谢。您可以尝试:
#first drop duplicates in each group by event
df = df.drop_duplicates(['event','cust'])
#count values
counts = df.cust.value_counts()
print counts
satya 3
panda 2
papu 2
def 1
normal 1
fgh 1
abc 1
Name: cust, dtype: int64
#get number of unique events
uniqevents = df.event.nunique()
print uniqevents
3
#get values with count == uniqevents
counts = counts[counts == uniqevents]
print counts
satya 3
Name: cust, dtype: int64
print counts.index.to_series().reset_index(drop=True)
0 satya
dtype: object
@jezrael在这种情况下很好(对于所有事件来说都是公共的)。但是如果我想要在某些选定事件中的cust,那该怎么办呢?比如获取事件et1和et2(不包括et3)的公共cust。好的。我必须先相应地过滤我的数据帧。df=df[df['events'].isin(['et1','et2']),然后我可以按照您的方法进行操作。只是想知道有没有熊猫函数(如果有的话)可以用来做它???是的,我想写一些类似于
isin
的东西。我不知道做这件事的功能。我尝试了groupby
,并apply
,但没有成功。