python中的偏移行函数?

2024-05-02 10:18:14 发布

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

如何编写一个python代码来计算新列的值--“UEC#u saving”by OFFSET#of rows in the“UEC”列。表格格式为dataframe。你知道吗

“偏移行”列中的正数表示下移行,反之亦然。你知道吗

例如,索引0的“UEC\u saving”为8.6-7.2,索引2的“UEC\u saving”为0.2-7.0

“UEC\ U保存”的输出应如下所示:

    Product_Class UEC  Offset_rows  UEC_saving
0      PC1         8.6     1           1.4
1      PC1         7.2     0           0.0
2      PC1         0.2    -1           -7.0
3      PC2         18.8    2           2.2
4      PC2         10.0    1           1.4
5      PC2         8.6     0           0.0
6      PC2         0.3    -1           -8.3

Tags: ofthe代码indataframeby格式表格
1条回答
网友
1楼 · 发布于 2024-05-02 10:18:14

你可以做:

for i,row in df.iterrows():
    df.at[i,'UEC_saving'] = row['UEC'] - df.loc[i+row['Offset_rows']]['UEC']

df

    UEC  Offset_rows  UEC_saving
0   8.6            1         1.4
1   7.2            0         0.0
2   0.2           -1        -7.0
3  18.8            2        10.2
4  10.0            1         1.4
5   8.6            0         0.0
6   0.3           -1        -8.3

除了索引3之外,这与你想要的答案是一致的,请告诉我是否有输入错误,或者请在你的问题中进一步解释到底发生了什么

相关问题 更多 >