Pandas concat 函数,每次迭代都分配了计数

Pandas concat function with count assigned for each iteration

在使用 concat 和索引复制数据帧时(参见示例 here),有没有一种方法可以为 c 列中的每次迭代分配一个计数变量(其中 c 列是计数变量)?

原始数据:

a b
0 1 2
1 2 3

df 使用 pd.concat[df]*5 和附加列 c:

进行了复制
a b c
0 1 2 1
1 2 3 1
0 1 2 2
1 2 3 2
0 1 2 3
1 2 3 3
0 1 2 4
1 2 3 4
0 1 2 5
1 2 3 5

这是一个多行数据框,其中计数变量必须应用于多行。

感谢您的想法!

您可以使用 np.arange and np.repeat:

N = 5
new_df = pd.concat([df] * N)
new_df['c'] = np.repeat(np.arange(N), df.shape[0]) + 1

输出:

>>> new_df
   a  b  c
0  1  2  1
1  2  3  1
0  1  2  2
1  2  3  2
0  1  2  3
1  2  3  3
0  1  2  4
1  2  3  4
0  1  2  5
1  2  3  5