miho
miho

Reputation: 12085

Group pandas DataFrame by given row indices

Let's assume we have a pandas DataFrame df and somehow computed a subsample of the indices of this DataFrame and we name this subsample idx. Now I want to group df by using idx in the sense that the first group contains every row from 0 to idx[0] (exclusive), the next group every row from idx[1] (inclusive) to idx[2] (exclusive), ..., until the last group which contains all rows from idx[len(idx)-1] to the last row.

The expected output would be structured similar to what you could realize by using groupby with a fixed time interval, but instead of splitting the rows by by a fixed time interval, they are split according to idx.

Is there any native Pandas way to do that? Or would I need to iterate over df myself and store it into a new DataFrame?

For testing purposes you can use the following randomly generated df and idx:

df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=["data"])
idx = df.sample(n=10).index

Upvotes: 0

Views: 139

Answers (1)

adnanmuttaleb
adnanmuttaleb

Reputation: 3624

I do not think there is a native way to do it, but I think you can get what you want like that:

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)

Output:

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')}

Upvotes: 1

Related Questions