Home > Software engineering >  Pandas: insert column from another df to new df at certain position
Pandas: insert column from another df to new df at certain position

Time:03-21

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.

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?

CodePudding user response:

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
  • Related