Skip to content
Advertisement

Changing a cell value in a columns based on a query from two other columns

I have a DataFrame with four columns: “date”, “time_gap”, “count” and “average_speed”.

I’d like to set values to the count column when requirements are met based on the “date” and “time_gap” columns.

So, for example, if I’m running this query:

JavaScript

It’s returning this as output:

JavaScript

Let’s say I want to change the value in the count columns with 12, how could I do it?

I’ve tried this:

JavaScript

Which returns this:

JavaScript

But when I’m having a look at the df:

JavaScript

I still have my row where the “count” is equal to 0:

JavaScript

How can I do it?

Advertisement

Answer

You can do it with loc, if you don’t want to use NumPy:

JavaScript

prints:

JavaScript

Yes, but in order to do that you have to use eval, which takes the expression passed in query, and evaluates it:

JavaScript

prints:

JavaScript

You can see practical applications of eval here.

Advertisement