[英]Fill values from one dataframe into another dataframe based on index of the two
I have two dataframes that contain time series data.我有两个包含时间序列数据的数据框。
Dataframe A contains data of timestep 1, with index values getting incremented by 1 each time.数据帧 A 包含时间步长 1 的数据,索引值每次递增 1。
Dataframe B contains data of timestep n
, with index values getting incremented by n each time.数据框 B 包含时间步长
n
的数据,索引值每次递增 n 。
I wish to do the following: Add a column in Dataframe A and fill values from Dataframe B such that if the index value of that row in A lies between that of consecutive indexes in B, I fill the same value for all such rows in A.我希望执行以下操作:在 Dataframe A 中添加一列并填充 Dataframe B 中的值,这样如果 A 中该行的索引值位于 B 中的连续索引之间,我为 A 中的所有此类行填充相同的值.
I will illustrate this as below:我将说明如下:
A:
id val1
0 2
1 3
2 4
3 1
4 6
5 23
6 2
7 12
8 56
9 34
10 90
...
B:
id tval
0 1
3 5
6 9
9 34
12 3434
...
Now, my result should like the following:现在,我的结果应该如下所示:
A:
id val1 tval
0 2 1
1 3 1
2 4 1
3 1 5
4 6 5
5 23 5
6 2 9
7 12 9
8 56 9
9 34 34
10 90 34
...
I would like to automate this for any n
.我想为任何
n
自动执行此操作。
Use merge_asof
:使用
merge_asof
:
df = pd.merge_asof(A, B, left_index=True, right_index=True)
print (df)
val1 tval
id
0 2 1
1 3 1
2 4 1
3 1 5
4 6 5
5 23 5
6 2 9
7 12 9
8 56 9
9 34 34
10 90 34
If id
is columns:如果
id
是列:
df = pd.merge_asof(A, B, on='id')
print (df)
id val1 tval
0 0 2 1
1 1 3 1
2 2 4 1
3 3 1 5
4 4 6 5
5 5 23 5
6 6 2 9
7 7 12 9
8 8 56 9
9 9 34 34
10 10 90 34
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.