2

Would anyone know how to convert the string output to a float? What I am attempting to do create separate data frames for "Month" and "day of the week" based on the time stamp index. The df.index.strftime outputs a string but I need a float based on the months numerical value (0-11 or 1-12 for a Jan thru December) and a day of the week numerical value (0-6 or 1-7 for Sunday thru Saturday)

from numpy.random import randint
import pandas as pd

# Create a df with a date-time index with data every 6 hours
rng = pd.date_range('1/5/2018 00:00', periods=5, freq='6H')
df = pd.DataFrame({'Random_Number':randint(1, 10, 5)}, index=rng)

# Getting different time information in the columns

df['month'] = df.index.strftime('%b')
df['Day_of_week'] = df.index.strftime('%a')

df
whatsinthename
  • 1,828
  • 20
  • 59
bbartling
  • 3,288
  • 9
  • 43
  • 88

1 Answers1

2

You need DatetimeIndex.month and DatetimeIndex.dayofweek:

df['month'] = df.index.month
df['Day_of_week'] = df.index.dayofweek
print (df)
                     Random_Number  month  Day_of_week
2018-01-05 00:00:00              1      1            4
2018-01-05 06:00:00              8      1            4
2018-01-05 12:00:00              4      1            4
2018-01-05 18:00:00              5      1            4
2018-01-06 00:00:00              1      1            5
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252