简体   繁体   中英

Copying existing columns between DataFrames

having a DataFrame with eg 10 columns (a, b, c...) and another smaller one with just let's say 3 of them (d, f, h), what is the 'best' way to copy the columns from the second DataFrame to the first?

The below seems to do the trick but I'm wondering if I should use join, merge or something else instead (for better performance/cleaner code)?

dfOutput = pd.DataFrame(columns=['a','b','c','d','e','f','g','h','i','j'])
melted = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]],columns=['d','h','i'])

dfOutput[melted.columns] = melted[melted.columns]

I believe you need df.merge() and df.reindex() :

melted.merge(dfOutput,on=['d','h','i'],how='left').reindex(dfOutput.columns,axis=1)

    a   b   c   d   e   f   g   h   i   j
0   NaN NaN NaN 1   NaN NaN NaN 2   3   NaN
1   NaN NaN NaN 4   NaN NaN NaN 5   6   NaN
2   NaN NaN NaN 7   NaN NaN NaN 8   9   NaN

you can reassign this to the first dataframe :

dfOutput = melted.merge(dfOutput,on=['d','h','i'],how='left').reindex(dfOutput.columns,axis=1)

Scenario 2 : If you already have data in certain columns , use dfOutput.update(melted) to update the first dataframe with the second:

For example:

dfOutput:

    a   b   c   d   e   f   g   h   i   j
0   NaN NaN NaN 1   NaN NaN NaN NaN NaN NaN
1   NaN NaN NaN 2   NaN NaN NaN NaN NaN NaN
2   NaN NaN NaN 3   NaN NaN NaN NaN NaN NaN

melted:

    d   h   i
0   5   6   7
1   4   8   6
2   7   4   9

>>dfOutput.update(melted)
>>dfOutput

    a   b   c   d   e   f   g   h   i   j
0   NaN NaN NaN 5   NaN NaN NaN 6   7   NaN
1   NaN NaN NaN 4   NaN NaN NaN 8   6   NaN
2   NaN NaN NaN 7   NaN NaN NaN 4   9   NaN

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