Created
March 22, 2018 01:39
-
-
Save okdolly-001/11160dcf5397cc8e2e87fb07133126cd to your computer and use it in GitHub Desktop.
Replace values in dataframe from another dataframe ? #pandas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your last example looks wrong. It references
df
anddf1
, but notdf2
. Are all thedf
references supposed to bedf2
? I think not, because you want to changedf1
. Maybe alldf
should bedf1
anddf1
should bedf2
?