简体   繁体   中英

Combine 2 dataframes with same index

I have 2 dataframes:

df1:

Date,      Time            Ln1        Ln2        Ln3
01.01.2020 0:00:00   274.18654  314.25631  238.30059
           1:00:00   274.25214  314.30739  238.32860
           2:00:00   274.31775  314.35846  238.35662
           3:00:00   274.38336  314.40953  238.38464
...                        ...        ...        ...
30.11.2020 20:00:00  238.25576  221.34272   16.99407
           21:00:00  238.32069  221.39448   17.00249
           22:00:00  238.38563  221.44625   17.01092
           23:00:00  238.45056  221.49801   17.01937
01.12.2020 0:00:00   238.51550  221.54977   17.02784

It has 3 columns (not 5,), because Date: Time is MultiIndex:

MultiIndex([(     'Date,',     'Time'),
            ('01.01.2020',  '0:00:00'),
            ('01.01.2020',  '1:00:00'),
            ('01.01.2020',  '2:00:00'),
            ('01.01.2020',  '3:00:00'),

My second DataFrame:

df2:

                  dt       price
0     20200103100000  256.086667
1     20200103110000  256.526667
2     20200103120000  257.386667
3     20200103130000  256.703333
4     20200103140000  255.320000

By the way, I know how to make df column an index (may be this is useful, may be not):

df_candles.set_index("dt", inplace = True)

My question: How to combine these two DataFrames? When I do:

pd = (df1, df1)

It really combines them, but creates 2 different tables:

Date,      Time            Ln1        Ln2        Ln3
01.01.2020 0:00:00   274.18654  314.25631  238.30059
           1:00:00   274.25214  314.30739  238.32860
           2:00:00   274.31775  314.35846  238.35662
           3:00:00   274.38336  314.40953  238.38464
...                        ...        ...        ...
30.11.2020 20:00:00  238.25576  221.34272   16.99407
           21:00:00  238.32069  221.39448   17.00249
           22:00:00  238.38563  221.44625   17.01092
           23:00:00  238.45056  221.49801   17.01937
01.12.2020 0:00:00   238.51550  221.54977   17.02784

                  dt       price
0     20200103100000  256.086667
1     20200103110000  256.526667
2     20200103120000  257.386667
3     20200103130000  256.703333
4     20200103140000  255.320000

But I want to merge them into 1 table. Additional row called 'Price' will be added into first dataframe. Date-Time index is a key to merge them.

try as below using merge

df1.merge(df2, left_on='lkey', right_on='Ln3')

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