简体   繁体   中英

split pandas data frame into multiple of 4 rows

I have a dataset of 100 rows, I want to split them into multiple of 4 and then perform operations on it, ie, first perform operation on first four rows, then on the next four rows and so on.

Note: Rows are independent of each other.

I don't know how to do it. Can somebody pls help me, I would be extremely thankful to him/her.

i will divide df per 2 row (simple example) and make list dfs

Example

df = pd.DataFrame(list('ABCDE'), columns=['value'])

df

    value
0   A
1   B
2   C
3   D
4   E

Code

grouper for grouping

grouper = pd.Series(range(0, len(df))) // 2

grouper

0    0
1    0
2    1
3    1
4    2
dtype: int64

divide to list

g = df.groupby(grouper)
dfs = [g.get_group(x) for x in g.groups]

result( dfs ):

[  value
 0     A
 1     B,
   value
 2     C
 3     D,
   value
 4     E]

Check

dfs[0]

output:

value
0   A
1   B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM