【问题标题】:Add a column for day of the week based on Date INdex根据日期索引为星期几添加一列
【发布时间】:2020-01-16 00:52:48
【问题描述】:

我是该语言的新手,并设法在下面创建了一个数据框。它是 MultiIndex 并且是 (a,b) 大小。 日期在行上,我不完全确定它是如何定义的。 我想根据左侧/索引上的日期戳添加一列,即星期几(1、2、3、4、5、6、7)。

谁能告诉我怎么做,我只是对如何拉索引/日期列进行计算感到困惑。

谢谢

print(df_3.iloc[:,0])
Date
2019-06-01     8573.84
2019-06-02     8565.47
2019-06-03     8741.75
2019-06-04     8210.99
2019-06-05     7704.34

2019-09-09    10443.23
2019-09-10    10336.41
2019-09-11    10123.03
2019-09-12    10176.82
2019-09-13    10415.36
Name: (bitcoin, Open), Length: 105, dtype: float64

【问题讨论】:

    标签: python dataframe dayofweek


    【解决方案1】:

    我刚刚使用了您的两个第一列和您的 3 个记录来获得可能的解决方案。这与 Celius 所做的差不多,但将列转换为 to_datetime。

    data = [['2019-06-01', 8573.84], ['2019-06-02', 8565.47], ['2019-06-03', 8741.75]] 
    
    df = pd.DataFrame(data,columns = ['Date', 'Bitcoin'])
    
    df['Date']= pd.to_datetime(df['Date']).dt.dayofweek
    

    输出结果为 2019-06-01(星期六)打印 5,为 2019-06-02(星期日)打印 6,为 2019-06-03(星期一)打印 0。

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      如果您使用的是 pandas 并且您的 Index 被解释为 Datetime 对象,我会尝试以下操作(我假设 Date 是您提供的数据框作为示例的索引):

      df = df.reset_index(drop=False) #Drop the index so you can get a new column named `Date`. 
      df['day_of_week'] = df['Date'].dt.dayofweek #Create new column using pandas `dt.dayofweek`
      

      编辑:Create a day of week column in a pandas dataframe也可能重复

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多