如果dataframe元素不同,则分配值

时间:2022-08-13 22:51:00

What is the equivalent Python/Pandas for the following R commands?

以下R命令的等效Python / Pandas是什么?

matrix1[!matrix2] <- 0

The goal is to compare two matrices, if the elements are different a zero should be assigned.

目标是比较两个矩阵,如果元素不同,则应分配零。

1 个解决方案

#1


1  

You can use the DataFrame where method:

您可以使用DataFrame where方法:

In [11]: df1 = pd.DataFrame([[1, 2], [3, 4]])

In [12]: df2 = pd.DataFrame([[1, 2], [3, 5]])

In [13]: df1.where(df1 == df2, 0)
Out[13]: 
   0  1
0  1  2
1  3  0

to do this inplace (modifying df):

在这里做这个(修改df):

In [14]: df.where(df==df1, 0, inplace=True)

#1


1  

You can use the DataFrame where method:

您可以使用DataFrame where方法:

In [11]: df1 = pd.DataFrame([[1, 2], [3, 4]])

In [12]: df2 = pd.DataFrame([[1, 2], [3, 5]])

In [13]: df1.where(df1 == df2, 0)
Out[13]: 
   0  1
0  1  2
1  3  0

to do this inplace (modifying df):

在这里做这个(修改df):

In [14]: df.where(df==df1, 0, inplace=True)