简体   繁体   中英

Altering values from a pandas DataFrame slice using different DataFrames

I want to assign values to a column of a pandas DataFrame using a slice from other DataFrame that have commom indexes. More or less like create a new column in a df1 filling the values from another DataFrame column (in the following example, df2['D']) that have the same index.

Example: I have two DataFrames, df1 and df2.

df1
          A         B
g                    
a  0.286074  0.148268
b  0.271671  0.356847
c  0.155908  0.951075

df2
          C         D
g                    
c  0.218612  0.296498
d  0.382499  0.900638

Now I want to add a new column to df1 with all values from df2['D'] that have the same index (row) in df1. I know that I can do something like this:

for g in df2.index:
    if g in df1.index.values.tolist():
        df1.loc[g, 'D'] = df2.loc[g, 'D']

df1
          A         B         D
g                              
a  0.286074  0.148268       NaN
b  0.271671  0.356847       NaN
c  0.155908  0.951075  0.296498

and works fine! But I think the solution is so ugly and is not using the power of pandas DataFrame at all.

I've tried to do something like the following, but did not work at all:

df1.reindex(df1.index.intersection(df2.index))['D'] = df2['D']

df1
          A         B
g                    
a  0.286074  0.148268
b  0.271671  0.356847
c  0.155908  0.951075

I've tried to do a bunch of other things using loc or queries, but none of them work.

This example was created based on what I need to do with tables containing large heavy data, this is why I want to optimize the result.

Thanks in advance!

Just assign it

df1['D']=df2.D
df1
          A         B         D
a  0.286074  0.148268       NaN
b  0.271671  0.356847       NaN
c  0.155908  0.951075  0.296498

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