Home > database >  Update the values of one column to other column based on condition
Update the values of one column to other column based on condition

Time:10-29

The values from column A to be replaced to column C if the column A values startswith '2'

Data

   A        B      C
12525    1FWE23   na       
14654    22354    na
24798    32684    na
28945    45368    na
46456    46485    na
2D545    45346    na
A5D66    58446    na

Expected

   A        B      C
12525    1FWE23   na       
14654    22354    na
24798    32684    24798
28945    45368    28945
46456    46485    na
2D545    45346    2D545
A5D66    58446    na

CodePudding user response:

# using loc identify the rows where column 'A' value starts with 'A',
# when true replace with 'C' with 'A'
df.loc[df['A'].str.startswith('2'), 'C'] = df['A']
df

        A       B   C
0   12525   1FWE23  na
1   14654   22354   na
2   24798   32684   24798
3   28945   45368   28945
4   46456   46485   na
5   2D545   45346   2D545
6   A5D66   58446   na
  • Related