如何用numpy数组中的相应值替换每行中特定索引中的值 [英] How to replace value in specific index in each row with corresponding value in numpy array

查看:89
本文介绍了如何用numpy数组中的相应值替换每行中特定索引中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框如下:

     datetime1 datetime2 datetime3 datetime4
id                                      
1    5          6         5         5   
2    7          2         3         5  
3    4          2         3         2 
4    6          4         4         7 
5    7          3         8         9 

我有一个像这样的numpy数组:

and I have a numpy array like this:

index_arr = [3, 2, 0, 1, 2]

此numpy数组分别引用我要替换的每一行中的索引.我要在替换中使用的值在另一个numpy数组中:

This numpy array refers to the index in each row, respectively, that I want to replace. The values I want to use in the replacement are in another numpy array:

replace_arr = [14, 12, 23, 17, 15]

使更新的数据框看起来像这样:

so that the updated dataframe looks like this:

     datetime1 datetime2 datetime3 datetime4
id                                      
1    5          6         5         14   
2    7          2         12        5  
3    23         2         3         2 
4    6          17        4         7 
5    7          3         15        9 

快速进行此更换的最佳方法是什么?我尝试使用枚举和迭代,但无法使用语法.感谢您的帮助-谢谢

What is the best way to go about doing this replacement quickly? I've tried using enumerate and iterrows but couldn't get the syntax to work. Would appreciate any help - thank you

推荐答案

这是使用 np.put_along_axis -

In [50]: df
Out[50]: 
   datetime1  datetime2  datetime3  datetime4
1          5          6          5          5
2          7          2          3          5
3          4          2          3          2
4          6          4          4          7
5          7          3          8          9

In [51]: index_arr = np.array([3, 2, 0 ,1 ,2])

In [52]: replace_arr = np.array([14, 12, 23, 17 ,15])

In [53]: np.put_along_axis(df.to_numpy(),index_arr[:,None],replace_arr[:,None],axis=1)

In [54]: df
Out[54]: 
   datetime1  datetime2  datetime3  datetime4
1          5          6          5         14
2          7          2         12          5
3         23          2          3          2
4          6         17          4          7
5          7          3         15          9

这篇关于如何用numpy数组中的相应值替换每行中特定索引中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆