Why my code didn't select data from Pandas dataframe? [duplicate]

余生长醉 提交于 2019-12-25 03:45:07

问题


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)
  1. How can I filter exact data from dataframe?
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!