Skip to content
Advertisement

Pandas dataframe slice left assignment

I want to do a left assignment of one column’s values between DataFrame slices where the indexes don’t match.

JavaScript

Is there a single expression that will work whether the left slice’s indexes are a subset or a superset of the right slice’s? The following attempt fails when left is a subset:

JavaScript

Advertisement

Answer

If you want the missing index in the left DataFrame

You can do a index union on df0.index and df2.index by Index.union followed by reindex() before assigning values of df2.index to df0, as follows:

JavaScript

Result:

JavaScript

If you don’t want the missing index in the left DataFrame

JavaScript

Result df0:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement