简体   繁体   中英

How to merge multiple data frame columns in pandas by using index?

I have six pandas data frames like the following. I want to join them by using the id column, which is the index. In the following, I have provided an example with three data frames.

df1 = 
id              cnt1
A000        10
A001        20
A002        30
A010        10
A050        55
...........................
A317        20

df2 = 
id          cnt2
A000        10
A010        20
...........................
A316        20

df3 = 
id          cnt3
A010        20
................................
A318        20

After joining, I need one data frame like the following.

all_df =
id              cnt1    cnt2    cnt3
A000            10      10      0   
A001            20      0       0
A002            30      0       0
A010            10      20      20
A050            55      0       0
............................................................................
A316            0       20      0
A317            20      0       0
A318            0       0       20

Please let me know how to do it. Thanks in advance.

IIUC, you want pd.concat on columns

all_df = pd.concat([df1, df2], axis=1).fillna(0)
print(all_df)

      cnt1  cnt2
id
A000  10.0  10.0
A001  20.0   0.0
A002  30.0   0.0
A010  10.0  20.0
A050  55.0   0.0
A317  20.0   0.0
A316   0.0  20.0

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