Pandas: Return Hour from Datetime Column Directly

前端 未结 7 1745
我在风中等你
我在风中等你 2020-11-30 03:19

Assume I have a DataFrame sales of timestamp values:

timestamp               sales_office
2014-01-01 09:01:00     Cincinnati
2014-01-01 09:11:00         


        
相关标签:
7条回答
  • 2020-11-30 03:40

    Assuming timestamp is the index of the data frame, you can just do the following:

    hours = sales.index.hour
    

    If you want to add that to your sales data frame, just do:

    import pandas as pd
    pd.concat([sales, pd.DataFrame(hours, index=sales.index)], axis = 1)
    

    Edit: If you have several columns of datetime objects, it's the same process. If you have a column ['date'] in your data frame, and assuming that 'date' has datetime values, you can access the hour from the 'date' as:

    hours = sales['date'].hour
    

    Edit2: If you want to adjust a column in your data frame you have to include dt:

    sales['datehour'] = sales['date'].dt.hour
    
    
    0 讨论(0)
提交回复
热议问题