将Pandas数据框中的索引行替换为另一个数据框中具有相应索引的值

时间:2019-11-06 10:07:31

标签: python pandas

我正在尝试编写一个函数,该函数在给定多个用户指定的时间步输入的情况下,将用另一个数据帧中的值覆盖给定索引处的值。例如:

df1

index   date  skew
92  2019-09-02  0
93  2019-09-03  0
94  2019-09-04  0
95  2019-09-05  0
96  2019-09-06  0
97  2019-09-09  0

df2

index  change
13      0.63
14      0.61
15      0.98
16      0.11
17      0.43

我追求的结果:

result_df

index   date         skew
92  2019-09-02  0
93  2019-09-03  0.63
94  2019-09-04  0.61
95  2019-09-05  0.98
96  2019-09-06  0.11
97  2019-09-09  0.43

使用for循环和df1.at[-i, 'skew'] = df2.loc[-i, 'change']

我得到以下结果:

index   date   skew
92  2019-09-02  0
93  2019-09-03  0
94  2019-09-04  0
95  2019-09-05  0
96  2019-09-06  0
97  2019-09-09  0
-5  NaT 0.63
-4  NaT 0.61
-3  NaT 0.98
-2  NaT 0.11
-1  NaT 0.43

我当前的功能:


    num_timesteps = 5

    def append_changes (df1, df2, num_timesteps):
      # Reverse loop to start from index df1.iloc[-num_timsteps:]
      for i in range(num_timesteps, 0, -1):
        df1.at[-i:, 'filler'] = df2.loc[-i:, 'change']
    return df1

我希望从索引-5(按照num_timesteps)到数据帧末尾的倾斜列下的行值将替换为df2中相同索引处的“ change”列中的那些值。

1 个答案:

答案 0 :(得分:2)

我认为没有循环是必要的,仅使用DataFrame.iloc的列位置为Index.get_loc来选择并设置新值-为避免匹配索引值分配由.values创建的numpy数组:

num_timesteps = 5
def append_changes (df1, df2, num_timesteps):
    arr = df2.iloc[-num_timesteps:, df2.columns.get_loc('change')].values
    df1.iloc[-num_timesteps:, df1.columns.get_loc('skew')] = arr
    return df1
print (append_changes(df1, df2, num_timesteps))
             date  skew
index                  
92     2019-09-02  0.00
93     2019-09-03  0.63
94     2019-09-04  0.61
95     2019-09-05  0.98
96     2019-09-06  0.11
97     2019-09-09  0.43