Skip to main content
 首页 » 编程设计

python之numpy/pandas/python 中用于搜索和替换的任何函数

2024年10月25日11sky-heaven

我有这样的 4x4 矩阵 ds1=

4  13  6  9  
7  12  5  7 
7  0  4  22   
9  8  12  0 

和其他包含两列的文件: ds2 =

4  1 
5  3 
6  1 
7  2 
8  2 
9  3 
12  1 
13  2 
22  3 
 
ds1 = ds1.apply(lambda x: ds2_mean[1] if [condition]) 

要添加什么条件来比较和检查 ds1 和 ds2 中的元素是否相等?

我想用矩阵 1 中的 col2 值替换第二个矩阵中的 col1 值,因此结果矩阵应该如下所示

1  2  1  3 
2  1  3  2 
2  0  1  3 
3  2  1  0 

请参阅Replacing mean value from one dataset to another这没有回答我的问题

请您参考如下方法:

如果您正在使用 numpy 数组,您可以这样做 -

# Make a copy of ds1 to initialize output array  
out = ds1.copy() 
 
# Find out the row indices in ds2 that have intersecting elements between  
# its first column and ds1 
_,C = np.where(ds1.ravel()[:,None] == ds2[:,0]) 
 
# New values taken from the second column of ds2 to be put in output 
newvals = ds2[C,1] 
 
# Valid positions in output array to be changed 
valid = np.in1d(ds1.ravel(),ds2[:,0]) 
 
# Finally make the changes to get desired output 
out.ravel()[valid] = newvals 

示例输入、输出-

In [79]: ds1 
Out[79]:  
array([[ 4, 13,  6,  9], 
       [ 7, 12,  5,  7], 
       [ 7,  0,  4, 22], 
       [ 9,  8, 12,  0]]) 
 
In [80]: ds2 
Out[80]:  
array([[ 4,  1], 
       [ 5,  3], 
       [ 6,  1], 
       [ 7,  2], 
       [ 8,  2], 
       [ 9,  3], 
       [12,  1], 
       [13,  2], 
       [22,  3]]) 
 
In [81]: out 
Out[81]:  
array([[1, 2, 1, 3], 
       [2, 1, 3, 2], 
       [2, 0, 1, 3], 
       [3, 2, 1, 0]])