根据日期索引添加星期几的列

时间:2019-09-14 12:43:19

标签: python dataframe dayofweek

我是该语言的新手,并且设法在下面创建了一个数据框。它是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

DF looks like this

2 个答案:

答案 0 :(得分:0)

如果您使用的是熊猫,并且您的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

的可能重复项

答案 1 :(得分:0)

我刚刚使用了您的第一列中的两列和您的记录中的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打印输出。

希望对您有帮助。