【问题标题】:pandas dataframe compare first and last row from each group熊猫数据框比较每组的第一行和最后一行
【发布时间】:2017-01-16 08:23:29
【问题描述】:

如何在不使用 groupby 函数的情况下比较 col a 分组中 col b 中第一行和 col b 中最后一行的值?因为 groupby 函数对于大型数据集来说非常慢。

a = [1,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3] 
b = [1,0,0,0,0,0,7,8,0,0,0,0,0,4,1,0,0,0,0,0,1]

返回两个列表:一个具有来自 col a 的组名,其中最后一个值大于第一个值,等等。

larger_or_equal = [1,3]
smaller = [2]

【问题讨论】:

  • 如果我理解了这个问题,我知道我有一个答案。你能做更多的工作来解释你在说什么吗?
  • 你试过groupby(sort=False)吗?这可以加快处理大型数据集的速度。
  • @piRSquared,13 组被选中,因为组中的最后一个元素大于或等于第一个元素。
  • Bryan,如果你能分享一下,我很想看看这三种解决方案之间的性能比较。

标签: pandas numpy dataframe


【解决方案1】:

全部numpy

a = np.array([1,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3]) 
b = np.array([1,0,0,0,0,0,7,8,0,0,0,0,0,4,1,0,0,0,0,0,1])

w = np.where(a[1:] != a[:-1])[0]  # find the edges
e = np.append(w, len(a) - 1)  # define the end pos
s = np.append(0, w + 1)  # define start pos

# slice end pos with boolean array.  then slice groups with end postions.
# I could also have used start positions.
a[e[b[e] >= b[s]]]
a[e[b[e] < b[s]]]

[1 3]
[2]

【讨论】:

  • 我猜应该更快!
  • 我没有测试过,但我假设那是True
【解决方案2】:

这是一个没有groupby 的解决方案。想法是移动列a 以检测组更改:

df[df['a'].shift() != df['a']]

    a  b
0   1  1
7   2  8
14  3  1

df[df['a'].shift(-1) != df['a']]

    a  b
6   1  7
13  2  4
20  3  1

我们将比较这两个数据框中的 b 列。我们只需要重置索引就可以进行 pandas 比较:

first = df[df['a'].shift() != df['a']].reset_index(drop=True)
last = df[df['a'].shift(-1) != df['a']].reset_index(drop=True)
first.loc[last['b'] >= first['b'], 'a'].values

array([1, 3])

然后对&lt; 执行相同操作以获取其他组。或者做一些不同的事情。


正如我在 cmets 中所写,groupby(sort=False) 可能会更快,具体取决于您的数据集。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多