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

Pandas: insert column from another df to new df at certain position

I have a df:

  A B C D
0 a f k p
1 b g l r
2 c h m s
3 d i n t
4 e j o u

And I want to update column B with a column

B
a
b
c

But at position n, meaning I will keep n-1 rows and update the rest.

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

So the output would be for updating at index 2:

  A B C D
0 a f k p
1 b a l r
2 c b m s
3 d c n t
4 e j o u

How would one do this?

>Solution :

IIUC, and assuming the first input is a dataframe df second input is a Series s:

n = 1 # second row (python indexes from 0)
df.update(s.set_axis(range(n, len(s)+n)))

output:

   A  B  C  D
0  a  f  k  p
1  b  a  l  r
2  c  b  m  s
3  d  c  n  t
4  e  j  o  u

input df:

  A B C D
0 a f k p
1 b g l r
2 c h m s
3 d i n t
4 e j o u

input s:

0    a
1    b
2    c
Name: B, dtype: object
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