根据其他列的条件获取列的值列表

Getting a list of values of a column depending on the conditions of other columns

对于给定的数据帧 df 为:

       Election Yr.  Party   Region Votes
   0     2000           A       a    50  
   1     2000           A       b    30
   2     2000           B       a    40
   3     2000           B       b    50  
   4     2000           C       a    30
   5     2000           C       c    40
   6     2004           A       a    20  
   7     2004           A       b    30
   8     2004           B       a    40
   9     2004           B       b    50  
   10    2004           C       a    60
   11    2004           C       b    40
   12    2008           A       a    30  
   13    2008           A       c    30
   14    2008           B       a    80
   15    2008           B       b    50  
   16    2008           C       a    60
   17    2008           C       b    40

如何找到在每次选举中都有不同获胜者的地区列表。获胜者由一年内政党的总票数决定。

首先你需要找出每个地区每次选举的获胜者,基本上是得票最高的政党。

winners = df.groupby(['Election Yr.', 'Region']).apply(lambda x: x.set_index('Party').Votes.idxmax())

然后您可以计算出每个地区有多少不同的获胜者:

n_unique_winners = winners.groupby(['Region']).nunique()

您还可以算出每个地区发生了多少次选举:

n_elections = winners.groupby(['Region']).size()

n_unique_winners == n_elections中具有真值的条目是您要查找的地区。

要获取这些区域的列表,您可以执行 n_unique_winners[n_unique_winners == n_elections].index.values