Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading