Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set values to rows of boolean filtered dataframe column

Tags:

python

pandas

I'm trying to set the values of "FreeSec" column to True for the filtered rows of my pandas dataframe. Here is the code:

data[data["Brand"].isin(group_clients)].FreeSec = True

However, when I check the values they are still set to False.

>>> data[data["Brand"].isin(group_clients)].FreeSec

12     False
163    False
164    False
165    False
166    False
167    False
168    False
169    False

What am I missing here?

like image 330
kannbaba Avatar asked Oct 21 '13 14:10

kannbaba


People also ask

How do you select rows of Pandas DataFrame based on values in a list?

isin() to Select Rows From List of Values. DataFrame. isin() method is used to filter/select rows from a list of values. You can have the list of values in variable and use it on isin() or use it directly.

How do I filter specific rows from a DataFrame Pandas?

You can use df[df["Courses"] == 'Spark'] to filter rows by a condition in pandas DataFrame. Not that this expression returns a new DataFrame with selected rows. You can also write the above statement with a variable.


1 Answers

You should use loc to do this without chaining, which will garauntee that assignment works:

data.loc[data["Brand"].isin(group_clients), "FreeSec"] = True

Assignment in loc is overridden so that the implementation detail of whether it's actually a view or a copy doesn't matter, it does matter if you chain so avoid/be very careful.

like image 173
Andy Hayden Avatar answered Oct 26 '22 14:10

Andy Hayden