问题
Why didn't my date filter work? All others filters work fine.
import pandas as pd
import datetime
data =pd.DataFrame({
'country': ['USA', 'USA', 'Belarus','Brazil'],
'time': ['2018-01-15 16:11:45.923570+00:00', '2018-01-15 16:19:45.923570+00:00', '2018-01-16 16:12:45.923570+00:00', '2018-01-17 16:14:45.923570+00:00']})
# Конвертируем в datetime
data['time'] = pd.to_datetime(data['time'])
# Конвертируем в date
data['time'] = data['time'].dt.date
print(data)
# Ищем дату '2018-12-12'
select_date = data.loc[data['time'] == '2018-01-17']
print(select_date)
- How can I filter exact data from dataframe?
How can I iterate dataframe by date daily?
for i in data: All rows in a specific day
I wish you all good luck and prosperity!
回答1:
datetime.date
objects are not vectorised with Pandas. The docs indicate this:
Returns numpy array of python
datetime.date
objects
Regular Python objects are stored in object
dtype series which do not support fancy date indexing. Instead, you can normalize:
data['time'] = pd.to_datetime(data['time'])
select_date = data.loc[data['time'].dt.normalize() == '2018-01-17']
You can use the same idea to iterate your dataframe by day:
for day, day_df in data.groupby(data['time'].dt.normalize()):
# do something with day_df
来源:https://stackoverflow.com/questions/53761721/why-my-code-didnt-select-data-from-pandas-dataframe