【问题标题】:Pandas concat function with count assigned for each iteration为每次迭代分配计数的 Pandas concat 函数
【发布时间】:2022-01-23 01:35:37
【问题描述】:

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

原df:

a b
0 1 2
1 2 3

使用pd.concat[df]*5 复制df 并使用附加的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

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

感谢您的意见!

【问题讨论】:

    标签: pandas dataframe indexing count concatenation


    【解决方案1】:

    您可以使用np.arangenp.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
    

    【讨论】:

      猜你喜欢
      • 2020-04-04
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 2015-08-16
      • 2023-03-25
      • 2023-01-16
      • 2020-08-09
      相关资源
      最近更新 更多