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

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

本文介绍了Pandas 时间序列数据索引从字符串到浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您需要 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

这篇关于Pandas 时间序列数据索引从字符串到浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:20