gpt4 book ai didi

python - 选择第 n 个中断组索引之前的列

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

我尝试从每个组的第一行中提取列c,但很难理解为什么组索引没有用g['c'].nth 保留(0) 方法。有什么想法吗?

>>> df = pd.DataFrame({'a': [1, 1, 2, 2], 'b': ['b', 'b', 'b', 'a'], 'c': [1, 2, 3, 4]})
>>> g = df.groupby(['a', 'b'])
>>> g.nth(0)
c
a b
1 b 1
2 a 4
b 3
>>> g['c'].nth(0)
0 1
2 3
3 4
Name: c, dtype: int64
>>>
>>> df = pd.DataFrame({'a': [1, 1, 2, 2], 'b': ['b', 'b', 'b', 'a'], 'c': [1, 2, 3, 4]})
>>> g = df.groupby(['a', 'b'])
>>> g.nth(0)
c
a b
1 b 1
2 a 4
b 3
>>> g['c'].nth(0)
0 1
2 3
3 4
Name: c, dtype: int64
>>> g.nth(0)['c']
a b
1 b 1
2 a 4
b 3
Name: c, dtype: int64
>>>

为什么g.nth(0)['c']g['c'].nth(0)不返回相同的Series(包括指数)?

更新

有趣的观察:

>>> g['c'].first()
a b
1 b 1
2 a 4
b 3
Name: c, dtype: int64

这正是我想要的,并且行为与 g['c'].nth(0) 不同。

最佳答案

我添加了新列 d 以进行更好的测试:

import pandas as pd
import numpy as np
import io


df = pd.DataFrame({'a': [1, 1, 2, 2], 'b': ['b', 'b', 'b', 'a'], 'c': [1, 2, 3, 4], 'd': [1, 2, 3, 4]})
print df
# a b c d
#0 1 b 1 1
#1 1 b 2 2
#2 2 b 3 3
#3 2 a 4 4
g = df.groupby(['a', 'b'])

#return SeriesGroupBy object and then apply nth
print g['c']
#<pandas.core.groupby.SeriesGroupBy object at 0x0000000014ED4EF0>
print g['c'].head()
#0 1
#1 2
#2 3
#3 4
#Name: c, dtype: int64
print g['c'].nth(0)
#0 1
#2 3
#3 4
#Name: c, dtype: int64
#return dataframe and then select c
print g.nth(0)
# c d
#a b
#1 b 1 1
#2 a 4 4
# b 3 3
print g.nth(0)['c']
#a b
#1 b 1
#2 a 4
# b 3
#Name: c, dtype: int64

编辑:

why I need to apply nth to the whole grouped dataframe

因为你需要先应用函数nth对于所有组,然后获取组的第一行。我尝试第二种方法。

在第一种方法中,您只需将 C 列与已计算的分组一起传递给 Series GroupBy 对象 link (查找新建:列选择)。它是一起df.groupby(['a', 'b'])['c'],然后应用函数nth。不适用于所有组df.groupby(['a', 'b'])

我认为存在链式函数,这取决于函数的顺序。

编辑1:

最后我报告了它 - 它看起来像 bug .

关于python - 选择第 n 个中断组索引之前的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34237462/

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