【问题标题】:How can I get pandas' groupby command to return a DataFrame instead of a Series?如何让 pandas\' groupby 命令返回 DataFrame 而不是 Series?
【发布时间】:2023-01-23 00:38:59
【问题描述】:

我不明白 pandas 的 groupby 的输出。我从一个包含 5 个字段/列(邮编、城市、位置、人口、州)的 DataFrame (df0) 开始。

 >>> df0.info()
 <class 'pandas.core.frame.DataFrame'>
 RangeIndex: 29467 entries, 0 to 29466
 Data columns (total 5 columns):
 zip      29467 non-null object
 city     29467 non-null object
 loc      29467 non-null object
 pop      29467 non-null int64
 state    29467 non-null object
 dtypes: int64(1), object(4)
 memory usage: 1.1+ MB

我想获得每个城市的总人口,但由于几个城市有多个邮政编码,我想我会使用 groupby.sum 如下:

  df6 = df0.groupby(['city','state'])['pop'].sum()

但是,这返回了一个 Series 而不是 DataFrame:

 >>> df6.info()
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "/usr/local/lib/python2.7/dist-packages/pandas/core/generic.py", line 2672, in __getattr__
     return object.__getattribute__(self, name)
  AttributeError: 'Series' object has no attribute 'info'
 >>> type(df6)
 <class 'pandas.core.series.Series'>

我希望能够使用类似于以下的方法查找任何城市的人口

 df0[df0['city'].isin(['ALBANY'])]

但是因为我有一个系列而不是一个 DataFrame,所以我不能。我也无法强制转换为 DataFrame。

我现在想知道的是:

  1. 为什么我没有返回 DataFrame 而不是 Series?
  2. 我怎样才能得到一张可以让我查询城市人口的表格?我可以使用从 groupby 获得的系列,还是应该采取不同的方法?

【问题讨论】:

  • 使用 as_index - df0.groupby(['city','state'], as_index=False)['pop'].sum()
  • 大熊猫是如此不直观:(只是有同样的问题

标签: python pandas


【解决方案1】:

需要groupbyreset_index 中的参数as_index=False 才能将MultiIndex 转换为列:

df6 = df0.groupby(['city','state'], as_index=False)['pop'].sum()

或者:

df6 = df0.groupby(['city','state'])['pop'].sum().reset_index()

样本:

df0 = pd.DataFrame({'city':['a','a','b'],
                   'state':['t','t','n'],
                   'pop':[7,8,9]})

print (df0)
  city  pop state
0    a    7     t
1    a    8     t
2    b    9     n

df6 = df0.groupby(['city','state'], as_index=False)['pop'].sum()
print (df6)
  city state  pop
0    a     t   15
1    b     n    9

df6 = df0.groupby(['city','state'])['pop'].sum().reset_index()
print (df6)
  city state  pop
0    a     t   15
1    b     n    9

最后选择loc,对于标量添加item()

print (df6.loc[df6.state == 't', 'pop'])
0    15
Name: pop, dtype: int64

print (df6.loc[df6.state == 't', 'pop'].item())
15

但如果只需要查找表,则可以使用SeriesMultiIndex

s = df0.groupby(['city','state'])['pop'].sum()
print (s)
city  state
a     t        15
b     n         9
Name: pop, dtype: int64

#select all cities by : and state by string like 't'
#output is Series of len 1
print (s.loc[:, 't'])
city
a    15
Name: pop, dtype: int64

#if need output as scalar add item()
print (s.loc[:, 't'].item())
15

【讨论】:

    【解决方案2】:

    没有样本数据很难明确地说,但是使用你显示的代码,返回一个系列,你应该能够通过使用类似df6.loc['Albany', 'NY']的东西来访问一个城市的人口(也就是说,按城市索引你的分组系列和状态)。

    你得到一个系列的原因是因为你选择了一个列('pop')在其上应用你的组计算。如果你将你的组计算应用于列列表,你会得到一个DataFrame。你可以通过这样做来做到这一点df6 = df0.groupby(['city','state'])[['pop']].sum()。(请注意'pop' 周围的额外括号,以选择一列而不是单列的列表。)但我不确定如果您可以使用上述方法访问无论如何,城市数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-08
      • 2018-11-18
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 2019-06-02
      • 2013-05-22
      相关资源
      最近更新 更多