【问题标题】:Pandas time series data Index from a string to float [duplicate]Pandas时间序列数据索引从字符串到浮动[重复]
【发布时间】:2018-07-15 13:51:04
【问题描述】:

有人知道如何将字符串输出转换为浮点数吗?我正在尝试根据时间戳索引为"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

【问题讨论】:

    标签: python pandas time-series


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 2018-12-28
      • 2018-08-28
      • 2018-05-15
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      相关资源
      最近更新 更多