Noob
Noob

Reputation: 174

Insert index in Dataframe

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

Upvotes: 2

Views: 5456

Answers (3)

BENY
BENY

Reputation: 323226

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

Upvotes: 1

jezrael
jezrael

Reputation: 862641

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

Upvotes: 1

Zero
Zero

Reputation: 76917

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

Upvotes: 2

Related Questions