Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate dataframe and series with different index

Tags:

python

pandas

if I have one dataframe and series like these

  bi            sm
0  A          0  a
1  B          1  b
2  C          2  C

I can concatenate like this

dfA['sm'] = dfB

  big  sm
0 A    a
1 B    b 
2 C    c

However I have one dataframe and seriese, each has the different index but same row numbers.

            bi            sm
2017-11-04  A          0  a
2017-11-03  B          1  b
2017-11-02  C          2  C 

I would like to concatenate these two into this

            bi  sm
2017-11-04  A   a
2017-11-03  B   b
2017-11-02  C   C 

How can I make it???

like image 527
whitebear Avatar asked Oct 20 '25 04:10

whitebear


2 Answers

Make both dataframes have the same index, then concatenate:

pd.concat([dfA, dfB.set_index(dfA.index)], axis=1)
#           bi sm
#2017-11-04  A  a
#2017-11-03  B  b
#2017-11-02  C  c
like image 186
DYZ Avatar answered Oct 21 '25 16:10

DYZ


You can assign dfB.sm as values values

Option 1

In [209]: dfA['sm'] = dfB.sm.values

In [210]: dfA
Out[210]:
           bi sm
2017-11-04  A  a
2017-11-03  B  b
2017-11-02  C  C

Option 2

In [215]: dfA.assign(smm=dfB.sm.values)
Out[215]:
           bi smm
2017-11-04  A   a
2017-11-03  B   b
2017-11-02  C   C

Note: dfA, dfB are both dataframes.

like image 24
Zero Avatar answered Oct 21 '25 16:10

Zero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!