【问题标题】:how to update a column containing date(yyyy-mm-dd) into weekday(wd) or weekend(we) in python using pandas如何使用熊猫在python中将包含日期(yyyy-mm-dd)的列更新为工作日(wd)或周末(we)
【发布时间】:2017-08-24 02:23:57
【问题描述】:

我有一个 CSV 文件,其中包含列中的用户 ID 和其他用户相关数据,其中一个是日期,现在我想将此日期列转换为该日期是周末(我们)还是工作日(wd),这对我有帮助在一些机器学习培训中,谢谢。

【问题讨论】:

    标签: python-2.7 pandas numpy


    【解决方案1】:

    我认为你需要numpy.wheredayofweek

    df['day'] = np.where(df['Date'].dt.dayofweek > 4, 'we', 'wd')
    

    示例:

    rng = pd.date_range('2017-04-03', periods=10)
    df = pd.DataFrame({'Date': rng, 'a': range(10)})  
    
    df['day'] = np.where(df['Date'].dt.dayofweek > 4, 'we', 'wd')
    print (df)
            Date  a day
    0 2017-04-03  0  wd
    1 2017-04-04  1  wd
    2 2017-04-05  2  wd
    3 2017-04-06  3  wd
    4 2017-04-07  4  wd
    5 2017-04-08  5  we
    6 2017-04-09  6  we
    7 2017-04-10  7  wd
    8 2017-04-11  8  wd
    9 2017-04-12  9  wd
    

    如果需要覆盖列:

    df['Date'] = np.where(df['Date'].dt.dayofweek > 4, 'we', 'wd')
    print (df)
      Date  a
    0   wd  0
    1   wd  1
    2   wd  2
    3   wd  3
    4   wd  4
    5   we  5
    6   we  6
    7   wd  7
    8   wd  8
    9   wd  9
    

    要在read_csv 中转换为日期时间,请使用参数parse_dates

    import pandas as pd
    from pandas.compat import StringIO
    
    temp=u"""datetime,YEAR
    2016-01-19,2016.0
    2016-01-20,2016.0
    2016-01-21,2016.0
    2016-01-22,2016.0
    2016-01-23,2016.0
    2017-02-02,2017.0"""
    #after testing replace 'StringIO(temp)' to 'filename.csv'
    df = pd.read_csv(StringIO(temp),  parse_dates=[0])
    
    print (df)
        datetime    YEAR
    0 2016-01-19  2016.0
    1 2016-01-20  2016.0
    2 2016-01-21  2016.0
    3 2016-01-22  2016.0
    4 2016-01-23  2016.0
    5 2017-02-02  2017.0
    
    print (df.dtypes)
    datetime    datetime64[ns]
    YEAR               float64
    dtype: object
    

    【讨论】:

    • 谢谢,但我收到错误:AttributeError: 'Series' object has no attribute 'dt'
    • df.dtypes 是什么?
    • user_id int64 lat float64 lon float64 city object **date object(timestamp) hour int64 dtype: object
    猜你喜欢
    • 1970-01-01
    • 2019-02-16
    • 2018-03-31
    • 2011-05-03
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多