简体   繁体   English

根据两者的索引将一个数据帧中的值填充到另一个数据帧中

[英]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.

相关问题 如何根据另外两个数据帧的值填充 Pandas 数据帧 - How to fill the Pandas Dataframe based on values from another two dataframes 根据第一个数据框中的数据填充另一个数据框中的值 - Fill values in another dataframe based on data from first one 从另一个大小的数据框中一一填充数据框中的空值 - Fill null values in a dataframe from another sized dataframe one by one 基于两个标准将值从一个数据帧映射到另一个数据帧 - Map Values from one dataframe to another based two criteria 熊猫从另一个数据帧填充一个数据帧上的空值 - Pandas fill empty values on one dataframe from another dataframe 如何将特定值从一个 dataframe 填充到另一个 dataframe - How to fill specific values from one dataframe to another dataframe Pandas:使用基于两列的另一个数据帧中的值替换一个数据帧中的值 - Pandas: replace values in one dataframe with values from another dataframe based on two columns 根据重复的日期时间索引,用另一个数据帧中的值覆盖一个数据帧 - Overwrite one dataframe with values from another dataframe, based on repeated datetime index 根据条件从另一个数据帧的值替换一个数据帧的值 - substitue values of one dataframe from values of another dataframe based on condition 根据对另一个 dataframe 的条件检查,过滤来自一个 dataframe 的值 - Filter values from one dataframe based on conditional checks on another dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM