0

I have two dataframes: df1 has data and df2 is kind of like a map for the data. (They are both the same size and are 2D). I would like to use pandas.where (or any method that isn't too convoluted) to replace the values of df1 based of the condition of the same cell in df2. For instance, if df2 is equal to 0, I want to set the same cell in df1 also to 0. How do I do this?

When I try the following I get an error:

df3 = df1.where(df2 == 0, other = 0)
smci
  • 32,567
  • 20
  • 113
  • 146
  • (Generally for clarity and brevity of code we name the dataframes `df1, df2, df3...` by default.) – smci May 07 '20 at 19:14
  • Generally you shouldn't need to handle multiple dataframes separately like this; if df1, df2 have the same shape and either the same index or some common column they can be joined/merged on (e.g. 'id'), then merge them. See **[Pandas Merging 101](https://stackoverflow.com/questions/53645882/pandas-merging-101)** – smci May 07 '20 at 19:18

2 Answers2

0
import pandas as pd

df = pd.DataFrame()
df_1 = pd.DataFrame()

df['a'] = [1,2,3,4,5]
df_1['b'] = [5,6,7,8,0]

This will give a sample df:

Now implement a loop, using range or len(df.index)

for i in range(0,5):
     df['a'][i] = np.where( df_1['b'][i] == 0, 0, df['a'][i])
Brijesh
  • 776
  • 5
  • 9
0

Generally you shouldn't need to handle multiple dataframes separately like this; if df1, df2 have the same shape and either the same index or some common column they can be joined/merged on (e.g. say it's named 'id'), then merge them:

df = pd.merge(df1, df2, on='id')

See Pandas Merging 101

smci
  • 32,567
  • 20
  • 113
  • 146