简体   繁体   中英

How to replace values in pandas dataframe with another dataframe

I have a dataframe (df1) that I want to replace the values in the symtom_1 , symptom_2 ... with the weight values from the df2 dataframe.

The first dataframe has 4000 rows and 17 columns

df1

   Disease            Symptom_1    Symptom_2    Symptom_3
0  Fungal infection   itching      itching      NaN
1  Fungal infection   skin_rash    itching      NaN
2  Fungal infection   itching      itching      NaN
3  Fungal infection   itching      itching      skin_rash
4  vertigo            itching      skin_rash    skin_rash
5  vertigo            vomiting     skin_rash    vomiting
6  vertigo            vomiting     skin_rash    vomiting
7  vertigo            vomiting     vomiting     skin_rash
8  Fungal infection   vomiting     vomiting     vomiting
9  Fungal infection   skin_rash    skin_rash    vomiting
10 Fungal infection   skin_rash    vomiting     itching

The second dataframe has 133 rows

df2

    Symptom              weight
0   itching                 1
1   skin_rash               3
2   nodal_skin_eruptions    4
3   continuous_sneezing     4
4   shivering               5

you can use replace and pass in a dictionary.

repl_dict = df2.set_index('Symptom')['weight'].to_dict()

print(df1.replace(repl_dict))

             Disease Symptom_1 Symptom_2 Symptom_3
0   Fungal infection         1         1       NaN
1   Fungal infection         3         1       NaN
2   Fungal infection         1         1       NaN
3   Fungal infection         1         1         3
4            vertigo         1         3         3
5            vertigo  vomiting         3  vomiting
6            vertigo  vomiting         3  vomiting
7            vertigo  vomiting  vomiting         3
8   Fungal infection  vomiting  vomiting  vomiting
9   Fungal infection         3         3  vomiting
10  Fungal infection         3  vomiting         1

repl_dict

{'itching': 1,
 'skin_rash': 3,
 'nodal_skin_eruptions': 4,
 'continuous_sneezing': 4,
 'shivering': 5}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM