繁体   English   中英

使用来自另一列的偏移量变量在Python中检索未来值

[英]Retrieving future value in Python using offset variable from another column

我试图弄清楚如何使用Python中单独行中的偏移量变量从未来日期检索值。 例如,我有下面的数据帧df ,我想找到一种方法来生成C列:

Orig A  Orig B  Desired Column C
54         1           76
76         4           46
14         3           46
35         1           -3
-3         0           -3
46         0           46
64         0           64
93         0           93
72         0           72

非常感谢任何帮助,谢谢!

您可以将NumPy用于矢量化解决方案:

import numpy as np

idx = np.arange(df.shape[0]) + df['OrigB'].values
df['C'] = df['OrigA'].iloc[idx].values

print(df)

   OrigA  OrigB   C
0     54      1  76
1     76      4  46
2     14      3  46
3     35      1  -3
4     -3      0  -3
5     46      0  46
6     64      0  64
7     93      0  93
8     72      0  72
import pandas as pd

dict = {"Orig A": [54,76,14,35,-3,46,64,93,72],
        "Orig B": [1,4,3,1,0,0,0,0,0],
        "Desired Column C": [76,46,46,-3,-3,46,64,93,72]}

df = pd.DataFrame(dict)

df["desired_test"] = [df["Orig A"].values[i+j] for i,j in enumerate(df["Orig B"].values)]

df

   Orig A  Orig B  Desired Column C  desired_test
0      54       1                76            76
1      76       4                46            46
2      14       3                46            46
3      35       1                -3            -3
4      -3       0                -3            -3
5      46       0                46            46
6      64       0                64            64
7      93       0                93            93
8      72       0                72            72

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM