Pandas - 将数据帧拆分为相等的行,并将新列中的数字分配为 case_id,从 1 开始递增,依此类推

Pandas - splitting dataframe into equal rows and assign number in new column as case_id in increasing order from 1 and so on

我有一个包含超过 100000 行的大型数据框。我想将行分成相等数量的块,比方说 4,并创建一个新列 case_id 并将数字 1 分配给这组 4 行。

id    col1   col2
0     A      A
1     B      B
2     C      C
3     D      D
4     E      E
5     F      F
6     G      G
7     H      H

id 从 0 开始。

期望的输出:

id    col1   col2    new_col_case_id
0     A      A       1
1     B      B       1
2     C      C       1
3     D      D       1
4     E      E       2
5     F      F       2
6     G      G       2
7     H      H       2

感谢任何帮助。

你可以试试这个:

import pandas as pd

n = 4 # number of rows in each chunk
data = {"id": [0,1,2,3,4,5,6,7],
        "col1": ["a", "b", "c", "d", "e", "f", "g", "h"],
        "col2": ["a", "b", "c", "d", "e", "f", "g", "h"]
        }
df = pd.DataFrame.from_dict(data)
length = len(df)
df["new_col_case_id"] = df["id"].apply(lambda x: int(x/n) + 1)
df = df.set_index("id") #optional
print(df)

输出:

   col1 col2  new_col_case_id
id                           
0     a    a                1
1     b    b                1
2     c    c                1
3     d    d                1
4     e    e                2
5     f    f                2
6     g    g                2
7     h    h                2