thedeg123
thedeg123

Reputation: 438

Pandas dataframe how to replace row with one with additional attributes

I have a method that adds additional attributes to a given pandas series and I want to update a row in the df with the returned series.

Lets say I have a simple dataframe: df = pd.DataFrame({'a':[1, 2], 'b':[3, 4]})

   a  b
0  1  3
1  2  4

and now I want to replace a row with one with additional attributes, all other rows will show Nan for that column ex:

subdf = df.loc[1]
subdf["newVal"] = "foo"  
# subdf is created externally and returned. Now it must be updated.
df.loc[1] = subdf #or something

df would look like:

   a  b newVal
0  1  3    Nan
1  2  4    foo

Upvotes: 1

Views: 188

Answers (1)

cs95
cs95

Reputation: 402814

Without loss in generalisation, first reindex and then assign with (i)loc:

df = df.reindex(subdf.index, axis=1)
df.iloc[-1] = subdf

df     
   a  b newVal
0  1  3    NaN
1  2  4    foo

Upvotes: 1

Related Questions