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

Add a numpy array with one value less to a pandas column

I have a pandas dataframe df:

A  B  C
1  2  NaN
2  3  NaN
4  5  NaN

How can I add a numpy array with the shape of 1 element less then the length of the dataframe, in this case, the numpy array:

[10 20]

And I want to start at the second row and fill the column C:

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
1  2  NaN
2  3  10
4  5  20

>Solution :

You can use:

l = [10, 20]

df.loc[df.index[1:1+len(l)], 'C'] = l

Or with iloc:

df.iloc[1:1+len(l), df.columns.get_loc('C')] = l

Output:

   A  B     C
0  1  2   NaN
1  2  3  10.0
2  4  5  20.0
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