Skip to content

Instantly share code, notes, and snippets.

@okdolly-001
Created March 22, 2018 01:39
Show Gist options
  • Save okdolly-001/11160dcf5397cc8e2e87fb07133126cd to your computer and use it in GitHub Desktop.
Save okdolly-001/11160dcf5397cc8e2e87fb07133126cd to your computer and use it in GitHub Desktop.
Replace values in dataframe from another dataframe ? #pandas
1. Substitute the NaN's in a dataframe with values from another dataframe
If you have two DataFrames of the same shape, then:
df[df.isnull()] = d2
2.Replace values in a dataframe with values from another dataframe by conditions
DataFrame.mask()
A = B.mask(condition, A)
When condition is true, the values from A will be used, otherwise B's values will be used.
3.
Is there a way to merge the values from one dataframe onto another without getting the _X, _Y columns? I'd like the values on one column to replace all zero values of another column.
df1:
Name Nonprofit Business Education
X 1 1 0
Y 0 1 0 <- Y and Z have zero values for Nonprofit and Educ
Z 0 0 0
Y 0 1 0
df2:
Name Nonprofit Education
Y 1 1 <- this df has the correct values.
Z 1 1
-----------------------
df.loc[df.Name.isin(df1.Name), ['Nonprofit', 'Education']] = df1[['Nonprofit', 'Education']]
df
Out[27]:
Name Nonprofit Business Education
0 X 1 1 0
1 Y 1 1 1
2 Z 1 0 1
3 Y 1 1 1
[4 rows x 4 columns]
@lsloan
Copy link

lsloan commented Aug 13, 2020

Your last example looks wrong. It references df and df1, but not df2. Are all the df references supposed to be df2? I think not, because you want to change df1. Maybe all df should be df1 and df1 should be df2?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment