zorro
zorro

Reputation: 117

How can I insert a Series into a DataFrame row?

I have a DataFrame like this:

import pandas as pd
import numpy as np
df = pd.DataFrame(columns=['a','b','c','d'], index=['x','y','z'])
df
     a    b    c    d
x  NaN  NaN  NaN  NaN
y  NaN  NaN  NaN  NaN
z  NaN  NaN  NaN  NaN

I also have a Series like this

s = pd.Series(np.random.randn(3), index=['b', 'c', 'd'])
s
b   -0.738283
c   -0.649760
d   -0.777346 
dtype: float64

I want to insert the Series into a row of the DataFrame, for example the 1th row, resulting the final DataFrame:

     a       b          c         d
x  NaN      NaN        NaN       NaN
y  NaN  -0.738283  -0.649760  -0.777346
z  NaN      NaN        NaN       NaN

How can I do it? thanks in advance ;)

Upvotes: 2

Views: 4015

Answers (2)

Vaibhav Kabdwal
Vaibhav Kabdwal

Reputation: 109

Just pass the series as an array:

df.iloc[1,1:] = np.asarray(s)

Output

Upvotes: 0

jezrael
jezrael

Reputation: 862601

You can use iloc if need select index of df by position:

#select second row (python counts from 0)
df.iloc[1] = s
print (df)
     a        b         c       d
x  NaN      NaN       NaN     NaN
y  NaN  1.71523  0.269975 -1.3663
z  NaN      NaN       NaN     NaN

Or ix (loc) if need select by label:

df.ix['y'] = s
df.loc['z'] = s
print (df)

     a         b         c         d
x  NaN       NaN       NaN       NaN
y  NaN  0.619316  0.917374 -0.559769
z  NaN  0.619316  0.917374 -0.559769

Upvotes: 3

Related Questions