如何移动 python pandas 数据框中的行

How to shift rows in python pandas dataframe

我有一个数据框,其中我需要在删除第一行并在每次迭代中最后添加 DFM 值为 100% 的新行后,将所有 10 行复制到这十行之下的第 50 次。就像下面的例子。

df1:-

    Cal     Group       DFM
     1     period 1    39.36%
     2     period 1    98.89
     3     period 1    99.95%
     4     period 1    99.97%
     5     period 1    99.99%
     6     period 1    100.00%
     7     period 1    100.00%
     8     period 1    100.00%
     9     period 1    100.00%
    10    period 1    100.00%
     

结果:- 我打印了 3 次并移动了 3 次值。但我需要一次又一次地重复这个动作 50 次。

    Cal     Group       DFM
     1     period 1    39.36%
     2     period 1    98.89
     3     period 1    99.95%
     4     period 1    99.97%
     5     period 1    99.99%
     6     period 1    100.00%
     7     period 1    100.00%
     8     period 1    100.00%
     9     period 1    100.00%
    10    period 1    100.00%
     1      period 1    98.89
     2     period 1    99.95%
     3     period 1    99.97%
     4     period 1    99.99%
     5     period 1    100.00%
     6     period 1    100.00%
     7     period 1    100.00%
     8     period 1    100.00%
     9     period 1    100.00%
    10    period 1    100.00%
     1     period 1    99.95%
     2     period 1    99.97%
     3     period 1    99.99%
     4     period 1    100.00%
     5     period 1    100.00%
     6     period 1    100.00%
     7     period 1    100.00%
     8    period 1    100.00%
     9    period 1    100.00%
    10    period 1    100.00%

您可以对数据框的 shifted 版本使用列表理解,然后 concatanate 它们在一起。为了使 CalGroup 不被计算,我们首先将它们设置为索引。此外,由于移位会导致 DFM 中的缺失值,我们将所需的填充值即 "100.00%" 传递给 shift。最后,我们重置索引以再次将 CalGroup 作为列:

df_with_new_idx = df.set_index(["Cal", "Group"])

repeat = 50
new_df = pd.concat([df_with_new_idx.shift(-j, fill_value="100.00%")
                    for j in range(repeat)])

new_df = new_df.reset_index()

为了说明而不是上面的 50 次重复 3 次,我得到:

>>> new_df

    Cal     Group      DFM
0     1  period 1   39.36%
1     2  period 1    98.89
2     3  period 1   99.95%
3     4  period 1   99.97%
4     5  period 1   99.99%
5     6  period 1  100.00%
6     7  period 1  100.00%
7     8  period 1  100.00%
8     9  period 1  100.00%
9    10  period 1  100.00%
10    1  period 1    98.89
11    2  period 1   99.95%
12    3  period 1   99.97%
13    4  period 1   99.99%
14    5  period 1  100.00%
15    6  period 1  100.00%
16    7  period 1  100.00%
17    8  period 1  100.00%
18    9  period 1  100.00%
19   10  period 1  100.00%
20    1  period 1   99.95%
21    2  period 1   99.97%
22    3  period 1   99.99%
23    4  period 1  100.00%
24    5  period 1  100.00%
25    6  period 1  100.00%
26    7  period 1  100.00%
27    8  period 1  100.00%
28    9  period 1  100.00%
29   10  period 1  100.00%