Home > Net >  Replace contents of a data frame from a list
Replace contents of a data frame from a list

Time:11-30

I want to replace the rows in column 'C' of the df that are also in int_cells list with the number 100.

I tried a for loop but I couldn't get it wo work.

Here is an example of what I am trying to do

import pandas as pd

df = pd.DataFrame({'A': [0, 1, 2, 3, 4, 2, 5, 8, 0, 1],
               'B': [5, 6, 7, 8, 9, 4, 5, 2, 6, 7],
               'C': [3, 5, 72, 74, 8, 3, 53, 21, 2, 36]})

int_cells = [72, 74, 8, 3, 53]

CodePudding user response:

I guess you can use list comprehension with conditional expression:

import pandas as pd

df = pd.DataFrame({'A': [0, 1, 2, 3, 4, 2, 5, 8, 0, 1],
               'B': [5, 6, 7, 8, 9, 4, 5, 2, 6, 7],
               'C': [3, 5, 72, 74, 8, 3, 53, 21, 2, 36]})

int_cells = [72, 74, 8, 3, 53]

df['C'] = [100 if x in int_cells else x for x in df.C]

print(df)
   # A  B    C
# 0  0  5  100
# 1  1  6    5
# 2  2  7  100
# 3  3  8  100
# 4  4  9  100
# 5  2  4  100
# 6  5  5  100
# 7  8  2   21
# 8  0  6    2
# 9  1  7   36

Or using isin and mask:

df.C.mask(df.C.isin(int_cells), 100, inplace=True)

CodePudding user response:

df.C[df.C.isin(int_cells)] = 100
  • Related