Search code examples
pythondataframedayofweek

Add a column for day of the week based on Date INdex


I'm new to the language and have managed to create a dataframe below. it is MultiIndex and is a (a,b) size. The Date is on the rows, and I'm not fully sure how it is all defined. I want to add a column that is the day of the week (1,2,3,4,5,6,7) for the days, based on the date stamps on the left/index.

Can someone show me how to do it please, I'm just confused on how to pull the index/date column to do calcs on.

Thanks

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


Solution

  • I've just used two of yours first columns and 3 of your records to get a possible solution. It's pretty much of what Celius did, but with a column conversion to 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
    

    The output result prints 5 for day 2019-06-01 which is a Saturday, 6 for the 2019-06-02 (Sunday) and 0 for 2019-06-03 (Monday).

    I hope it helps you.