Home > Mobile >  How to move a single value in a pd dataframe to another column?
How to move a single value in a pd dataframe to another column?

Time:06-19

Let's say I have a single value in a dataframe that is not in its place. For example:

df_ABCACA = pd.DataFrame({'Date': ['2020-10-01', 'Z', '2021-01-01', '2021-10-01'],
                   'ID': [101, '2020-01-01', 102, 102],
                   'number': [10, 10, 11, 11]})

How can I move the value now placed in column ID row 1 ('2020-01-01') to column Date in the same row?

CodePudding user response:

You can use .loc[] like below with selecting row number:

# with df.loc[]
df_ABCACA.loc[1, 'Date'] = df_ABCACA.loc[1, 'ID']

Or without row number you can write a mask and find the value then set it where you want :

mask = df_ABCACA['ID'] == '2020-01-01'
df_ABCACA.loc[mask, 'Date'] = df_ABCACA.loc[mask, 'ID']
print(df_ABCACA)

Or with numpy.where:

import numpy as np
df_ABCACA['Date'] = np.where(df_ABCACA['ID'] == '2020-01-01', 
                             df_ABCACA['ID'], 
                             df_ABCACA['Date'])

Output:

         Date          ID  number
0  2020-10-01         101      10
1  2020-01-01  2020-01-01      10
2  2021-01-01         102      11
3  2021-10-01         102      11
  • Related