2017-04-26 103 views
0

让我们说,我有一个数据帧,我希望用户与各国相关联:的熊猫数据帧寻找最常见的发生

>>> dfUsers[['userId', 'country', 'lat']].dropna().groupby(['userId', 'country']).agg(len).reset_index() 

       userId  country lat 
0 1479705782818706665  India 1 
1 1480576924651623757  India 12 
2 1480576924651623757   РФ 2 
3 1480928137574356334  Malaysia 17 
4 1480988896538924406  India 1 
5 1481723517601846740  Malaysia 2 
6 1481810347655435765 Singapore 3 
7 1481818704328005112 Singapore 6 
8 1482457537889441352 Singapore 18 
9 1482488858703566411 Singapore 1 
10 148273India 1 
11 1483106342385227382 Singapore 2 
12 1483316566673069712  Malaysia 4 
13 1484507758001657608 Singapore 6 
14 1484654275131873053 Singapore 1 
15 1484666213119301417 Singapore 1 
16 1484734631705057076  Malaysia 4 

我想要做的,是关联的一个用户一个国家。在这种情况下,很容易看到用户1480576924651623757有两个不同的国家与他/她相关联。但是,我想将此用户与India关联,因为用户在印度的次数超过了他/她在其他国家/地区的次数。

有没有这样做的简单方法?我总是可以遍历'userId'并找到相应的大值。不过,我想知道是否有这似乎这样做没有环路的一种方式......

+0

'lat'列是用于count'user' +'country'吗? – jezrael

+0

这只是一个虚拟的专栏群... – ssm

回答

1

需要idxmaxlat列找到最大值每个组索引,然后通过loc选择:

df = df.loc[df.groupby('userId')['lat'].idxmax()] 
print (df) 
       userId country lat 
0 1479705782818706665  India 1 
1 1480576924651623757  India 12 < 12 is max, so India 
3 1480928137574356334 Malaysia 17 
4 1480988896538924406  India 1 
5 1481723517601846740 Malaysia 2 
6 1481810347655435765 Singapore 3 
7 1481818704328005112 Singapore 6 
8 1482457537889441352 Singapore 18 
9 1482488858703566411 Singapore 1 
10 148273India 1 
11 1483106342385227382 Singapore 2 
12 1483316566673069712 Malaysia 4 
13 1484507758001657608 Singapore 6 
14 1484654275131873053 Singapore 1 
15 1484666213119301417 Singapore 1 
16 1484734631705057076 Malaysia 4 

df = dfUsers[['userId', 'country', 'lat']].dropna() 
              .groupby(['userId', 'country']) 
              .size() 
              .reset_index(name='Count') 

df = df.loc[df.groupby('userId')['Count'].idxmax()]