Cooper
Cooper

Reputation: 83

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

Upvotes: 0

Views: 49

Answers (1)

Ferris
Ferris

Reputation: 5601

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.

Upvotes: 1

Related Questions