5

I have a pandas dataframe and I want to index a subset of rows using two conditions, then replace that subset with a new dataframe I've created. However as you can see below it only replaces the rows that have the same indices. How do I align the indices of the dataframes so the replacement will work for all rows?

df = pd.DataFrame({'A': [-4, 9, 6, -3],
                   'B': ['y', 'b', 'b','x']})

df
Out[581]: 
   A  B
0 -4  y
1  9  b
2  6  b
3 -3  x

replacement = pd.DataFrame({'A':[-7, -4], 'B':['y','x']})

replacement
Out[583]: 
   A  B
0 -7  y
1 -4  x

df.loc[(df['A']>0) & (df['B']=='b')] = replacement

df
Out[585]: 
     A    B
0 -4.0    y
1 -4.0    x
2  NaN  NaN
3 -3.0    x
2
  • df.loc[(df['A']>0) & (df['B']=='b')] = replacement.to_numpy() ? Commented Feb 12, 2020 at 12:35
  • >>> df.loc[(df['A']>0) & (df['B']=='b')] = replacement.values Commented Feb 12, 2020 at 12:36

1 Answer 1

4

IIUC you want

>>> df.loc[(df['A']>0) & (df['B']=='b')] = replacement.values
>>> df
   A  B
0 -4  y
1 -7  y
2 -4  x
3 -3  x
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.