Home > database >  Pandas assign series to another Series based on index
Pandas assign series to another Series based on index

Time:01-20

I have three Pandas Dataframes:

df1:

0        NaN
1        NaN
2        NaN
3        NaN
4        NaN
5        NaN
6        NaN
7        NaN
8        NaN
9        NaN

df2:

0        1
3        7
6        5
9        2

df3:

1        2
4        6
7        6

My goal is to assign the values of df2 and df3 to df1 based on the index. df1 should then become:

0        1
1        2
2        NaN
3        7
4        6
5        NaN
6        5
7        6
8        NaN
9        2

I tried with simple assinment:

df1.loc[df2.index] = df2.values

or

df1.loc[df2.index] = df2

but this gives me an ValueError: ValueError: Must have equal len keys and value when setting with an iterable

Thanks for your help!

CodePudding user response:

You can do concat with combine_first:

pd.concat([df2,df3]).combine_first(df1)

Or reindex:

pd.concat([df2,df3]).reindex_like(df1)

0  1.0
1  2.0
2  NaN
3  7.0
4  6.0
5  NaN
6  5.0
7  6.0
8  NaN
9  2.0
  • Related