2

This is my dataframe df :

df = pd.DataFrame({'a': [0.671399,0.446172,0.614758], 
                   'b' : [ 0.101208 ,-0.243316 ,0.075793],
                   'c':[-0.181532 ,0.051767, -0.451460]})

       a            b           c       
0   0.671399    0.101208    -0.181532   
1   0.446172    -0.243316   0.051767
2   0.614758    0.075793    -0.451460   

I wanted to add 1 more column with more index so I tried this:

df['e'] = pd.Series(data = [-0.335485, -1.166658, -0.385571,-1.166658 ],index=[0,1,2,3])  

But the result is not adding index = 3 row.

       a           b           c           e
0   0.671399    0.101208    -0.181532   -0.335485
1   0.446172    -0.243316   0.051767    -1.166658
2   0.614758    0.075793    -0.451460   -0.385571

3 Answers 3

2

Using join

In [2794]: s = pd.Series(data=[-0.335485, -1.166658, -0.385571,-1.166658 ],
                         index=[0,1,2,3])

In [2795]: df.join(pd.DataFrame({'e': s}), how='outer')
Out[2795]:
          a         b         c         e
0  0.671399  0.101208 -0.181532 -0.335485
1  0.446172 -0.243316  0.051767 -1.166658
2  0.614758  0.075793 -0.451460 -0.385571
3       NaN       NaN       NaN -1.166658
Sign up to request clarification or add additional context in comments.

Comments

1

Add name for Series and use concat with default outer join or join - need specify outer join, becaue by default left:

s = pd.Series(data = [-0.335485, -1.166658, -0.385571,-1.166658 ],index=[0,1,2,3], name='e')
df = pd.concat([df, s], axis=1)
#alternative solution
#df = df.join(s, how='outer')
print (df)
          a         b         c         e
0  0.671399  0.101208 -0.181532 -0.335485
1  0.446172 -0.243316  0.051767 -1.166658
2  0.614758  0.075793 -0.451460 -0.385571
3       NaN       NaN       NaN -1.166658

Another way for set name to Series is use rename:

s = pd.Series(data = [-0.335485, -1.166658, -0.385571,-1.166658 ],index=[0,1,2,3])
df = df.join(s.rename('e'), how='outer')
print (df)
          a         b         c         e
0  0.671399  0.101208 -0.181532 -0.335485
1  0.446172 -0.243316  0.051767 -1.166658
2  0.614758  0.075793 -0.451460 -0.385571
3       NaN       NaN       NaN -1.166658

Comments

1

Here is another way by using combine_first

df['e']=np.nan
df.combine_first(s.to_frame().rename(columns={0:'e'}))
Out[374]: 
          a         b         c         e
0  0.671399  0.101208 -0.181532 -0.335485
1  0.446172 -0.243316  0.051767 -1.166658
2  0.614758  0.075793 -0.451460 -0.385571
3       NaN       NaN       NaN -1.166658

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.