按给定的行索引对pandas DataFrame进行分组

时间:2019-07-13 13:09:56

标签: python pandas

让我们假设我们有一个熊猫DataFrame @foreach ($blogs as $blog) <div class="blog-item"> <div class="blog-thumb"> <img src="asset/img/blog/1.jpg" alt=""> ->this is where i was supposed to fetch the image </div> <div class="blog-text text-box text-white"> <div class="top-meta">{{ Carbon\Carbon::parse($blog->created_at)->format('d-m-Y') }} / di <a href="">Rakitan</a></div> <h3>{{ $blog->name }}</h3> <p>{!! \Illuminate\Support\Str::words($blog->message, 30, '...') !!}</p> <a href="{{ route('post.read', ['blog_id' => $blog->id]) }}" class="read-more">Lanjutkan Baca <img src="asset/img/icons/double-arrow.png" alt="#"/></a> </div> </div> @endforeach ,并以某种方式计算了此DataFrame索引的一个子样本,并将其命名为df。现在,我要使用idx来对df进行分组,因为第一组包含从idx0(不包括)的每一行,下一组则是{ {1}}(包括)到idx[0](包括),...,直到包含从idx[1]到最后一行的所有行的最后一组。

预期输出的结构类似于使用带有固定时间间隔的idx[2]会实现的结果,但是不是按照固定的时间间隔对行进行拆分,而是根据{{1} }。

有没有本地的Pandas方式?还是我需要自己遍历idx[len(idx)-1]并将其存储到新的DataFrame中?

出于测试目的,您可以使用以下随机生成的groupbyidx

df

1 个答案:

答案 0 :(得分:1)

我认为没有做到这一点的本地方法,但是我认为您可以得到想要的结果:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=["data"])
idx = np.sort(df.sample(n=10).index)
ind = np.digitize(df.index, idx, right=False)
print('Intervals:', idx)
print('Groups', df.groupby(ind).groups)

输出:

Intervals: [ 3 15 19 42 46 48 54 81 88 98]
Groups {0: Int64Index([0, 1, 2], dtype='int64'), 1: Int64Index([3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], dtype='int64'), 2: Int64Index([15, 16, 17, 18], dtype='int64'), 3: Int64Index([19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
            36, 37, 38, 39, 40, 41],
           dtype='int64'), 4: Int64Index([42, 43, 44, 45], dtype='int64'), 5: Int64Index([46, 47], dtype='int64'), 6: Int64Index([48, 49, 50, 51, 52, 53], dtype='int64'), 7: Int64Index([54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
            71, 72, 73, 74, 75, 76, 77, 78, 79, 80],
           dtype='int64'), 8: Int64Index([81, 82, 83, 84, 85, 86, 87], dtype='int64'), 9: Int64Index([88, 89, 90, 91, 92, 93, 94, 95, 96, 97], dtype='int64'), 10: Int64Index([98, 99], dtype='int64')}