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

标签 python numpy matrix pandas

我有这样的 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 中的元素是否相等?

我希望将第二个矩阵中的 col1 值替换为矩阵 1 中的 col2 值,因此生成的矩阵应如下所示

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]])

关于python - numpy/pandas/python 中用于搜索和替换的任何函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30067356/

相关文章:

arrays - 通过对 R 中不同索引求和来矢量化(或加速)双循环

python - Django导入/导出: ForeignKey fields return None

python - Beautifulsoup 功能在特定场景下无法正常工作

python - Django:属性和查询集注释之间的重复逻辑

python - 将 Numpy 数组插入 Mysql 数据库

python - 将 PIL 黑白图像转换为 Numpy 数组时出错

r - 将 dist 对象列表保存到 R 中的表

matlab - MATLAB 中 [] 和 [1x0] 的区别

python - numpy.outer() 真的比转置快吗?

python - 从多个线程调用 NumPy 的 C API 函数有什么含义?