首页 > 解决方案 > 如何在数据框中的每 11 个位置插入 -1?

问题描述

我有以下数据框:在每 11 行我想插入-1。尝试了一些建议,但没有得到我的预期。

图像1

标签: pythonpandasdataframe

解决方案


也许你可以使用pandas.DataFrame.iloc

>>> import pandas as pd
>>> d = {'%UNWEIGHTED_ILI': [0.184361, 0.527357, 0.330384, 0.100392,
                             0.491726, 0.433408, 0.117853, 0.129628,
                             0.204399, 0.342965, 0.123456, 0.976543]}
>>> df = pd.DataFrame(data=d)
>>> df
    %UNWEIGHTED_ILI
0          0.184361
1          0.527357
2          0.330384
3          0.100392
4          0.491726
5          0.433408
6          0.117853
7          0.129628
8          0.204399
9          0.342965
10         0.123456
11         0.976543
>>> df.iloc[::11, :] -= 1
>>> # df.iloc[11::11, :] -= 1 If you don't want -1 to be added to the first row
>>> df
    %UNWEIGHTED_ILI
0         -0.815639
1          0.527357
2          0.330384
3          0.100392
4          0.491726
5          0.433408
6          0.117853
7          0.129628
8          0.204399
9          0.342965
10         0.123456
11        -0.023457

推荐阅读