Pandas时间序列数据索引从字符串到浮点数

时间:2018-02-05 16:30:26

标签: python pandas time-series

有谁知道如何将字符串输出转换为浮点数?我尝试做的是根据时间戳索引为"Month""day of the week"创建单独的数据帧。 df.index.strftime输出一个字符串,但我需要float基于月份数值(1月到12月为0-11或1-12)和星期几数值(0-6)或周日至周六的1-7)

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

1 个答案:

答案 0 :(得分:1)

您需要DatetimeIndex.monthDatetimeIndex.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