【问题标题】:Slice pandas dataframe in groups of consecutive values在连续值组中切片 pandas 数据帧
【发布时间】:2014-11-25 03:08:35
【问题描述】:

我有一个数据框,其中包含最终“跳过”(即增加超过 1)的连续值部分。我想拆分数据框,类似于groupby 函数(字母索引仅供展示):

    A
a   1
b   2
c   3
d   6
e   7
f   8
g   11
h   12
i   13

# would return

a   1
b   2
c   3
-----
d   6
e   7
f   8
-----
g   11
h   12
i   13

【问题讨论】:

  • 一个更好的测试用例打破假设子序列必须不重叠的代码是df = pd.DataFrame({'A': [1,2,3,6,7,8,7,8,9]}, index = list('abcdefghi'))

标签: python pandas slice


【解决方案1】:

略微提高了回答速度...

for k,g in df.groupby(df['A'] - np.arange(df.shape[0])):
    print g

【讨论】:

  • 非常非常聪明...谢谢
  • 如何更新这个以按两列分组?我似乎无法理清语法。
  • @SummerEla 只需将其放入数组中,例如df.groupby([colA,colB])
  • 这对原始数据过于依赖,将在df = pd.DataFrame({'A': [1,2,3,6,7,8,7,8,9]}, index = list('abcdefghi')) 上中断。此解决方案假定偏移量 df['A'] - np.arange(df.shape[0]) 在组中是唯一的,这已被破坏。
【解决方案2】:

我的两分钱只是为了好玩。

In [15]:

for grp, val in df.groupby((df.diff()-1).fillna(0).cumsum().A):
    print val
   A
a  1
b  2
c  3
   A
d  6
e  7
f  8
    A
g  11
h  12
i  13

【讨论】:

  • 轻微改进:df.groupby( df['A'].diff().ne(1).cumsum() )
  • df.diff() ... .A 并且只在最后取列 A 如果 df 有任何非数字列,则会中断,无论如何它会区分所有列,而不仅仅是 A。
【解决方案3】:

我们可以使用shift来比较行之间的差异是否大于1,然后构造一个所需索引的元组对列表:

In [128]:
# list comprehension of the indices where the value difference is larger than 1, have to add the first row index also
index_list = [df.iloc[0].name] + list(df[(df.value - df.value.shift()) > 1].index)
index_list
Out[128]:
['a', 'd', 'g']

我们必须构造一个我们感兴趣的范围的元组对列表,注意在 pandas 中包含 beg 和 end 索引值,因此我们必须找到前一行的标签作为结束范围标签:

In [170]:

final_range=[]
for i in range(len(index_list)):
    # handle last range value
    if i == len(index_list) -1:
        final_range.append((index_list[i], df.iloc[-1].name ))
    else:
        final_range.append( (index_list[i], df.iloc[ np.searchsorted(df.index, df.loc[index_list[i + 1]].name) -1].name))

final_range

Out[170]:
[('a', 'c'), ('d', 'f'), ('g', 'i')]

我使用 numpy 的 searchsorted 来查找索引值(基于整数),我们可以在其中插入我们的值,然后从中减去 1 以获得上一行的索引标签值

In [171]:
# now print
for r in final_range:
    print(df[r[0]:r[1]])
       value
index       
a          1
b          2
c          3
       value
index       
d          6
e          7
f          8
       value
index       
g         11
h         12
i         13

【讨论】:

    猜你喜欢
    • 2019-07-22
    • 2021-10-17
    • 2015-06-06
    • 2018-01-30
    • 2019-10-09
    • 1970-01-01
    • 2019-10-02
    • 2018-02-12
    • 2018-06-10
    相关资源
    最近更新 更多