简体   繁体   中英

concat 2 dataframes by multiindex

Here I have two Nx1 dataframes(ds and code are indices, not columns). My purpose is, for each day, to concat open and close by code.

df1:

ds          code       open
20160101    001         1.4
            002         1.3
            003         1.2
```         ```         ```
20201231    001         12.3
            003         2.4
            007         3.4

and

df2:

ds          code       close
20160101    001         1.5
            002         1.12
            003         1.21
```         ```         ```
20201231    001         14.5
            003         2.2
            007         3.3

My ideal result is

ds          code       open       close
20160101    001         1.4         1.5
            002         1.3         1.12
            003         1.2         1.21
```         ```         ```
20201231    001         12.3        14.5
            003         2.4         2.2
            007         3.4         3.3

I tried to use the following method but it does not work

df = pd.concat([df1,df2], axis = 0)

No matter I add "keys" or "levels", I could not get the wanted result, any help would be appreciated

you can use join or merge to merge two dataframe.

df = df1.join(df2, how='outer')

if the index is not unique, pd.concat with axis=1 will not work.

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