python - 使用 : groupby and nlargest() in pandas 的结果更奇怪

标签 python pandas group-by

此问题是以下帖子的延伸:select largest N of a column of each groupby group using pandas

让我们使用相同的 df 和所选答案中提出的解决方法。基本上,我正在尝试执行 2 个 groupby 操作并选择每个组中最大的 N 个。但是,正如您在下面看到的,其中一项操作出现错误。

鉴于原始帖子在代码中发现了一个错误 (see here),我想知道是否存在另一个错误或同一错误的另一种表现形式?

不幸的是,在这些问题得到解决和解决之前,我的工作停滞不前。我们可以请注意一下这个问题吗?我明天才能提供赏金。

df:

{'city1': {0: 'Chicago',
  1: 'Chicago',
  2: 'Chicago',
  3: 'Chicago',
  4: 'Miami',
  5: 'Houston',
  6: 'Austin'},
 'city2': {0: 'Toronto',
  1: 'Detroit',
  2: 'St.Louis',
  3: 'Miami',
  4: 'Dallas',
  5: 'Dallas',
  6: 'Dallas'},
 'p234_r_c': {0: 5.0, 1: 4.0, 2: 2.0, 3: 0.5, 4: 1.0, 5: 4.0, 6: 3.0},
 'plant1_type': {0: 'COMBCYCL',
  1: 'COMBCYCL',
  2: 'NUKE',
  3: 'COAL',
  4: 'NUKE',
  5: 'COMBCYCL',
  6: 'COAL'},
 'plant2_type': {0: 'COAL',
  1: 'COAL',
  2: 'COMBCYCL',
  3: 'COMBCYCL',
  4: 'COAL',
  5: 'NUKE',
  6: 'NUKE'}}

您可以使用上面的字典生成 df: pd.DataFrame(dct)

首先groupby:似乎生成了有意义的结果

cols = ['city2','plant1_type','plant2_type']
df.set_index(cols).groupby(level=cols)['p234_r_c'].nlargest(1).reset_index()

    city2   plant1_type plant2_type p234_r_c
0   Toronto COMBCYCL    COAL        5.0
1   Detroit COMBCYCL    COAL        4.0
2   St.Louis    NUKE    COMBCYCL    2.0
3   Miami   COAL        COMBCYCL    0.5
4   Dallas  NUKE        COAL        1.0
5   Dallas  COMBCYCL    NUKE        4.0
6   Dallas  COAL        NUKE        3.0

第二个 groupby: 产生一个错误。唯一的区别是 city1使用而不是 city2 .

cols = ['city1','plant1_type','plant2_type']
df.set_index(cols).groupby(level=cols)['p234_r_c'].nlargest(1).reset_index()

错误结果:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-443-6426182b55e1> in <module>()
----> 1 test1.set_index(cols).groupby(level=cols)['p234_r_c'].nlargest(1).reset_index()

C:\Users\user1\Anaconda3\lib\site-packages\pandas\core\series.py in reset_index(self, level, drop, name, inplace)
    967         else:
    968             df = self.to_frame(name)
--> 969             return df.reset_index(level=level, drop=drop)
    970 
    971     def __unicode__(self):

C:\Users\user1\Anaconda3\lib\site-packages\pandas\core\frame.py in reset_index(self, level, drop, inplace, col_level, col_fill)
   2944                     level_values = _maybe_casted_values(lev, lab)
   2945                     if level is None or i in level:
-> 2946                         new_obj.insert(0, col_name, level_values)
   2947 
   2948         elif not drop:

C:\Users\user1\Anaconda3\lib\site-packages\pandas\core\frame.py in insert(self, loc, column, value, allow_duplicates)
   2447         value = self._sanitize_column(column, value)
   2448         self._data.insert(loc, column, value,
-> 2449                           allow_duplicates=allow_duplicates)
   2450 
   2451     def assign(self, **kwargs):

C:\Users\user1\Anaconda3\lib\site-packages\pandas\core\internals.py in insert(self, loc, item, value, allow_duplicates)
   3508         if not allow_duplicates and item in self.items:
   3509             # Should this be a different kind of error??
-> 3510             raise ValueError('cannot insert %s, already exists' % item)
   3511 
   3512         if not isinstance(loc, int):

ValueError: cannot insert plant2_type, already exists

最后:

我怎样才能得到 city1使用 ['city2','plant1_type','plant2_type'] 的 groupby 结果中的列和 city2使用 ['city1','plant1_type','plant2_type'] 的 groupby 结果中的列?

想知道对应的city1使用 ['city2','plant1_type','plant2_type'] 的 groupby 值和相应的city2使用 ['city1','plant1_type','plant2_type'] 的 groupby 值.

更新:

为什么下面的结果结构完全不同?唯一的区别是 city2在#A while city1 中使用用于#B。

一个)

cols = ['city2','plant1_type','plant2_type']
test1.set_index(cols).groupby(level=cols)['p234_r_c'].nlargest(1)


city2     plant1_type  plant2_type
Toronto   COMBCYCL     COAL           5.0
Detroit   COMBCYCL     COAL           4.0
St.Louis  NUKE         COMBCYCL       2.0
Miami     COAL         COMBCYCL       0.5
Dallas    NUKE         COAL           1.0
          COMBCYCL     NUKE           4.0
          COAL         NUKE           3.0
Name: p234_r_c, dtype: float64

B)

cols2 = ['city1','plant1_type','plant2_type']
test1.set_index(cols2).groupby(level=cols2)['p234_r_c'].nlargest(1)

city1    plant1_type  plant2_type  city1    plant1_type  plant2_type
Austin   COAL         NUKE         Austin   COAL         NUKE           3.0
Chicago  COAL         COMBCYCL     Chicago  COAL         COMBCYCL       0.5
         COMBCYCL     COAL         Chicago  COMBCYCL     COAL           5.0
         NUKE         COMBCYCL     Chicago  NUKE         COMBCYCL       2.0
Houston  COMBCYCL     NUKE         Houston  COMBCYCL     NUKE           4.0
Miami    NUKE         COAL         Miami    NUKE         COAL           1.0
Name: p234_r_c, dtype: float64

最佳答案

试试这个:

In [76]: df.groupby(cols2)['p234_r_c'].nlargest(1).reset_index(level=3, drop=True).reset_index()
Out[76]:
     city1 plant1_type plant2_type  p234_r_c
0   Austin        COAL        NUKE       3.0
1  Chicago        COAL    COMBCYCL       0.5
2  Chicago    COMBCYCL        COAL       5.0
3  Chicago        NUKE    COMBCYCL       2.0
4  Houston    COMBCYCL        NUKE       4.0
5    Miami        NUKE        COAL       1.0

坦率地说,我不理解以下行为:

In [77]: df.set_index(cols2).groupby(level=cols2)['p234_r_c'].nlargest(1)
Out[77]:
city1    plant1_type  plant2_type  city1    plant1_type  plant2_type
Austin   COAL         NUKE         Austin   COAL         NUKE           3.0
Chicago  COAL         COMBCYCL     Chicago  COAL         COMBCYCL       0.5
         COMBCYCL     COAL         Chicago  COMBCYCL     COAL           5.0
         NUKE         COMBCYCL     Chicago  NUKE         COMBCYCL       2.0
Houston  COMBCYCL     NUKE         Houston  COMBCYCL     NUKE           4.0
Miami    NUKE         COAL         Miami    NUKE         COAL           1.0
Name: p234_r_c, dtype: float64

哪里:

In [78]: cols2
Out[78]: ['city1', 'plant1_type', 'plant2_type']

关于python - 使用 : groupby and nlargest() in pandas 的结果更奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41986261/

相关文章:

python - 什么是 "inheritable alternative constructors"?

python - 循环遍历 2 个 Pandas Dataframes 并将行值传递给计算距离的函数

mysql - 获取不同的行以及字段的总和

python - 列上的 Pandas Multiindex Groupby

python - 是否可以在 ReferenceFields 上使用 unique_with ?

python线程,如何返回多线程代码执行过程中产生的结果

python - 如何融化 0 和 1 的数据帧并仅保留 1

mysql - 按共同日期对行进行分组

python - 如何获得 TkInter GUI(不是 shell 提示符)以监听来自/dev/stdin 的输入

python - 与python拟合的直方图