Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

assign values of one dataframe column to another dataframe column based on condition

am trying to compare two dataframes based on different columns and assign a value to a dataframe based on it.

df1 :

date    value1  value2
4/1/2021    A   1
4/2/2021    B   2
4/6/2021    C   3
4/4/2021    D   4
4/5/2021    E   5
4/6/2021    F   6
4/2/2021    G   7

df2:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Date    percent
4/1/2021    0.1
4/2/2021    0.2
4/6/2021    0.6

output:

date    value1  value2  per
4/1/2021    A   1       0.1
4/2/2021    B   2       0.2
4/6/2021    C   3       0.6
4/4/2021    D   4       0
4/5/2021    E   5       0
4/6/2021    F   6       0
4/2/2021    G   7       0.2

Code1:

df1['per'] = np.where(df1['date']==df2['Date'], df2['per'], 0)

error:

ValueError: Can only compare identically-labeled Series objects

Note: changed the column value of df2[‘Date] to df2[‘date] and then tried merging
code2:

new = pd.merge(df1, df2, on=['date'], how='inner')

error:

ValueError: You are trying to merge on object and datetime64[ns] columns. If you wish to proceed you should use pd.concat

>Solution :

df1['per']=df1['date'].map(dict(zip(df2['Date'], df2['percent']))).fillna(0)



      date value1  value2  per
0  4/1/2021      A       1  0.1
1  4/2/2021      B       2  0.2
2  4/6/2021      C       3  0.6
3  4/4/2021      D       4  0.0
4  4/5/2021      E       5  0.0
5  4/6/2021      F       6  0.6
6  4/2/2021      G       7  0.2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading