Python数据帧插值向数据帧添加新行

2024-06-07 17:26:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,当EVM=一个特定值(-30)时,我想添加一个新行,并用线性插值更新其他列

Index    PwrOut      EVM       PwrGain    Vout

0    -0.760031   -58.322902  32.239969  134.331851

1   3.242575    -58.073389  32.242575   134.332376

2   7.246203    -57.138122  32.246203   134.343538

3   11.251078   -54.160870  32.251078   134.383609

4   15.257129   -48.624869  32.257129   134.487430

5   17.260618   -45.971596  32.260618   134.586753

6   18.263079   -44.319692  32.263079   134.656616

7   19.266674   -41.532695  32.266674   134.743599

8   20.271934   -37.546253  32.271934   134.849050

9   21.278990   -33.239208  32.278990   134.972439


10  22.286989   -29.221786  32.286989   135.111068

11  23.293533   -25.652448  32.293533   135.261357

例如,(在第3列中)EVM=-30位于上面第9行和第10行之间。如何包含EVM=-30的新行(第9行和第10行之间),然后使用基于EVM列在第9行和第10行中的数字之间的位置的线性插值来更新其他列(仅此新行中)? 如果能够搜索并找到EVM=-30所在的行,那就太好了。 是否可以对某些行应用线性插值,而对其他列应用非线性插值

谢谢


Tags: 数据index数字evmvoutpwroutpwrgain
1条回答
网友
1楼 · 发布于 2024-06-07 17:26:05

到目前为止,插值是最容易的部分。这里有一种方法

首先,找到缺少的行并逐个添加:

targets = (-50, -40, -30)  # Arbitrary
idxs = df.EVM.searchsorted(targets)  # Find the rows location
arr = df.values
for idx, target in zip(idxs, targets):
    arr = np.insert(arr, idx, [np.nan, target, np.nan, np.nan], axis=0)

df1 = pd.DataFrame(arr, columns=df.columns)

然后您可以实际插入:

df2 = df1.interpolate('linear')

输出:

       PwrOut        EVM    PwrGain        Vout
0   -0.760031 -58.322902  32.239969  134.331851
1    3.242575 -58.073389  32.242575  134.332376
2    7.246203 -57.138122  32.246203  134.343538
3   11.251078 -54.160870  32.251078  134.383609
4   13.254103 -50.000000  32.254103  134.435519
5   15.257129 -48.624869  32.257129  134.487430
6   17.260618 -45.971596  32.260618  134.586753
7   18.263079 -44.319692  32.263079  134.656616
9   19.266674 -41.532695  32.266674  134.743599
8   19.769304 -40.000000  32.269304  134.796324
11  20.271934 -37.546253  32.271934  134.849050
12  21.278990 -33.239208  32.278990  134.972439
10  21.782989 -30.000000  32.282989  135.041753
13  22.286989 -29.221786  32.286989  135.111068
14  23.293533 -25.652448  32.293533  135.261357

如果要按列使用自定义插值方法,请单独使用,例如:

df2.PwrOut = df1.PwrOut.interpolate('cubic')

相关问题 更多 >

    热门问题