numpy/pandas/python中任何要搜索和表示的函数

2024-06-28 19:36:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的4x4矩阵 ds1=

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

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

^{pr2}$

要添加什么条件来比较和检查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这不能回答我的问题


Tags: 文件from元素value矩阵mean条件one
2条回答

这是另一个解决方案。使用DataFrame.replace()功能。在

df1.replace(to_replace= df2[0].tolist(), value= df2[1].tolist, inplace=True)

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

# 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

样本输入,输出-

^{pr2}$

相关问题 更多 >