Set specific rows values to column in pandas dataframe using list comprehension

I would like to change values in a column for specific rows. The rows are defined in a vector containing the row indexes. I thought this could be done with list comprehension (similar to apply function in R). I tried this:

[(dataframe.loc[(dataframe['id']== x), 'column_to_be_changed'] = 1) (x) for x in indexes]

The error message is "SyntaxError: invalid syntax" with pointer to " = 1 "

This part works:

x = n (e.g. 5)
dataframe.loc[(dataframe['id']== x), 'column_to_be_changed'] = 1)

Since a list comprehension gives a list back and not pandas dataframe, I am missing something, I guess. Help would be much appreciated. Thanks.

>Solution :

I think you are just looking for mask or where. See the below example:

df=pd.DataFrame({'id': [1,2,3,4], 'some_column': ['a','b','c','d']})
print(df)
#    id some_column
# 0   1           a
# 1   2           b
# 2   3           c
# 3   4           d

li = [1,2] #indexes 1 and 2, so b and c
mask = df.index.isin(li)
df['some_column'].mask(mask, 'z', inplace=True) # 'z' is the value that will be set if the index is in 'li'
print(df)
#    id some_column
# 0   1           a
# 1   2           z
# 2   3           z
# 3   4           d

Leave a Reply