gpt4 book ai didi

python - 如何让 pandas 的 groupby 命令返回 DataFrame 而不是 Series?

转载 作者:太空宇宙 更新时间:2023-11-03 14:07:27 24 4
gpt4 key购买 nike

我不明白 pandas 的 groupby 的输出。我从一个包含 5 个字段/列( zip 、城市、位置、人口、州)的 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'])]

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

我现在想知道的是:

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

最佳答案

需要参数 as_index=False groupbyreset_indexMultiIndex 转换为列:

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

关于python - 如何让 pandas 的 groupby 命令返回 DataFrame 而不是 Series?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42324077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com