0

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
3
  • df.loc[:,'c'] = series Commented Apr 19, 2022 at 13:18
  • @rhug123 this only creates a new column called c with all values as NaN Commented Apr 19, 2022 at 13:21
  • my apologies, i didnt read the question close enough Commented Apr 19, 2022 at 13:27

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

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.