How do u filter data in pandas by columns of different datatype

Question:

I’m having this issue where I got one date table of datetime dtype and another column of float type. Example – DateColumn (year-month-day) and Salary of type float.
How can I take all the rows of lets say 2019 where the salary is higher than 2000.

Asked By: Bojan

||

Answers:

Say you have the data in this way:

date = pd.date_range("2019-01-01", periods=500, freq="D")
salary = np.random.randint(100, 10000, 500)
df = pd.DataFrame({"date": date, "salary": salary})

Then you can just select:

 df[(df["date"].dt.year == 2019) & (df["salary"] > 2000)]

If your date column is a string (df["date"] = df["date"].astype(str)), then you can do:

df[(df["date"] >= "2019-01-01") & (df["date"] <= "2019-12-31") & (df["salary"] > 2000)]
Answered By: mlang
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.