Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pandas groupby agg关于保留没有as_索引参数的组列不一致_Python_Pandas_Types - Fatal编程技术网

Python pandas groupby agg关于保留没有as_索引参数的组列不一致

Python pandas groupby agg关于保留没有as_索引参数的组列不一致,python,pandas,types,Python,Pandas,Types,在2列数据框的2列上进行分组,使列保持为列: >>> df = pandas.DataFrame({'a':[1,2,3],'b':[4,5,6]}) >>> df a b 0 1 4 1 2 5 2 3 6 [3 rows x 2 columns] >>> df.groupby(['a','b']).agg(sum) a b a b 1 4 1 4 2 5 2 5 3 6 3 6

在2列数据框的2列上进行分组,使列保持为列:

>>> df = pandas.DataFrame({'a':[1,2,3],'b':[4,5,6]})
>>> df
   a  b
0  1  4
1  2  5
2  3  6

[3 rows x 2 columns]
>>> df.groupby(['a','b']).agg(sum)
     a  b
a b      
1 4  1  4
2 5  2  5
3 6  3  6

[3 rows x 2 columns]
>>> df.groupby(['a','b'], as_index=False).agg(sum)
   a  b  c
0  1  4  7
1  2  5  8
2  3  6  9

[3 rows x 3 columns]
但在3列数据帧的2列上分组会将这些列变成索引:

>>> df = pandas.DataFrame({'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]})
>>> df
   a  b  c
0  1  4  7
1  2  5  8
2  3  6  9

[3 rows x 3 columns]
>>> df.groupby(['a','b']).agg(sum)
     c
a b   
1 4  7
2 5  8
3 6  9

[3 rows x 1 columns]
作为\u index=False传递一致地返回列:

>>> df = pandas.DataFrame({'a':[1,2,3],'b':[4,5,6]})
>>> df
   a  b
0  1  4
1  2  5
2  3  6

[3 rows x 2 columns]
>>> df.groupby(['a','b']).agg(sum)
     a  b
a b      
1 4  1  4
2 5  2  5
3 6  3  6

[3 rows x 2 columns]
>>> df.groupby(['a','b'], as_index=False).agg(sum)
   a  b  c
0  1  4  7
1  2  5  8
2  3  6  9

[3 rows x 3 columns]

这里的最佳做法是始终使用as_index=False,以便阅读您的代码的人知道会发生什么?

第一个行为让我感到困惑,可能是一个不推荐的功能?在Python 3.4.1、Pandas 0.16.1和我得到以下结果:

df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})
df.groupby(['a','b']).agg(sum)

Empty DataFrame
Columns: []
Index: []

在这里,您似乎感到困惑,列是索引的一部分,因为您对它们进行了分组,在此基础上调用了sum,最终结果实际上是相同的df,但列“a”和“b”作为索引。在后一种情况下,它会再次求和,但由于您有重复的行,那么您会看到最终df中的差异。我不确定默认行为应该是什么,但标准情况是您没有对分组所依据的相同列求和(或其他),因此您的示例对我来说似乎非常人工。这并不是对这个问题的批评,我只是不确定你到底关心什么样的实际情况。我认为如果
as_index=False
输出确实是您想要的,那么是的,您应该显式地指定它b/c,我不希望隐式地指定它。如果您喜欢
as_index=False
结果,则应明确指定。2列的情况似乎很奇怪,但这是一件奇怪的事情,甚至尝试。熊猫似乎默认为
,但不清楚原因。@maxymoo为2列报告的结果是我在看到结果之前所期望的结果。我在0.16.1和python 2.7中得到了与您相同的结果(空数据帧)。我倾向于同意提问者的第一个行为令人困惑。看起来结果应该是一个空的数据帧,正如您在0.16.1.hmm中发现的一样——我使用的是pandas 0.13.1。我猜我正在处理一个早已修复的bug。我将投票结束这个问题。