Shashidhar
Shashidhar

Reputation: 95

How to replace row values in a particular column using index?

I have the following data frames,

data frame- 1 (named as df1)

index   A   B   C
1       q   a   w
2       e   d   q
3       r   f   r
4       t   g   t
5       y   j   o
6       i   k   p
7       j   w   k
8       i   o   u
9       a   p   v
10      o   l   a

data frame- 2 (named as df2)

index   C
3       a
7       b
9       c
10      d

I tried to replace the rows for specific indexes in the column "C" using the data frame - 2 for the data frame - 1 but I got the following result after using the below code:

df1['C'] = df2

Output:

index   A   B   C
1       q   a   NaN
2       e   d   NaN
3       r   f   a
4       t   g   NaN
5       y   j   NaN
6       i   k   NaN
7       j   w   b
8       i   o   NaN
9       a   p   c
10      o   l   d

But I want something like this,

Expected output:

index   A   B   C
1       q   a   w
2       e   d   q
3       r   f   a
4       t   g   t
5       y   j   o
6       i   k   p
7       j   w   b
8       i   o   u
9       a   p   c
10      o   l   d

So clearly I don't need NaN values in column "C" instead I want the values to remain as it is. (I mean it should change only for that particular index value).

Please let me know the solution.

Thanks in advance!

Upvotes: 1

Views: 967

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150735

Assuming index is the actual index column, we can do loc:

df1.loc[df2.index, 'C'] = df2['C']

Or even more simple with:

df1.update(df2)

Output:

       A  B  C
index         
1      q  a  w
2      e  d  q
3      r  f  a
4      t  g  t
5      y  j  o
6      i  k  p
7      j  w  b
8      i  o  u
9      a  p  c
10     o  l  d

Upvotes: 2

Ajay A
Ajay A

Reputation: 1068

Try this

for idx, row in df2.iterrows():
    df1.at[idx, 'C'] = row['C']

Upvotes: 1

Related Questions