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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.