【问题标题】:Merging Date and Hour in Pandas在 Pandas 中合并日期和时间
【发布时间】:2022-01-07 09:33:59
【问题描述】:

我在 Pandas DataFrame 中有两列,一列包含作为字符串的日期,另一列包含作为 int 的一天中的小时。

我想把它转换成日期时间戳。

我已经做到了,但感觉速度很慢。

数据是:

df = pd.DataFrame({'Date': {0: '01/12/2017',
                            1: '01/12/2017',
                            2: '01/12/2017',
                            3: '01/12/2017',
                            4: '01/12/2017'},
                   'Hour': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4},
                   'Rented Bike Count': {0: 254, 1: 204, 2: 173, 3: 107, 4: 78}})

Date 的 dtypes 是 objectHourint64

我目前正在使用以下方式合并日期和时间:

# Generate the datetime column
df['datetime'] = pd.to_datetime(df.apply(lambda x: f"{x['Date']} {x['Hour']}:00:00", axis=1))

# Remove the old datetime columns
df = df.drop('Date', axis=1).drop('Hour', axis=1)

有更快的方法吗?

【问题讨论】:

    标签: python python-3.x pandas datetime


    【解决方案1】:

    我愿意:

    # is your data day-first or month-first?
    df['datetime'] = pd.to_datetime(df['Date'], dayfirst=True) + pd.to_timedelta(df['Hour'], unit='H')
    
    df = df.drop(['Date','Hour'], axis=1)
    

    【讨论】:

    • 这就是我想要的。正在努力使pd.to_timedelta() 工作。此外,这是第一天。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多