Home > database >  Using .loc[index] to set a rows value by index and add any additional columns
Using .loc[index] to set a rows value by index and add any additional columns

Time:04-19

Is it possible to use .loc[] to set a rows value (using a series) as well as add any additional columns that might exist in this series. Perhaps there is a type of merge I am unaware of that could merge a series into a dataframe by index.

import pandas as pd
index = 1
series = pd.Series({'a':2, 'b':54, 'c':945})
df = pd.DataFrame({'a': {0: 1, 1: 2, 2: 3}, 'b': {0: 3, 1: 54, 2: 1}})
df.loc[index] = series

output:

   a   b
0  1   3
1  2  54
2  3   1

Desired output:

   a  b  c
0  1  3  
1  2  54 945
2  3  1

CodePudding user response:

You can use index of the series as columns:

>>> df.loc[index, series.index] = series
>>> df
   a   b      c
0  1   3    NaN
1  2  54  945.0
2  3   1    NaN

CodePudding user response:

You can reindex the dataframe first:

df2 = df.reindex(columns=series.index)
df2.loc[index] = series

Alternatively, use combine_first:

df2 = df.combine_first(series.to_frame(name=index).T)

output:

   a   b      c
0  1   3    NaN
1  2  54  945.0
2  3   1    NaN
  • Related