首页 > 解决方案 > 如何矢量化熊猫日期时间列?

问题描述

我正在尝试使用矢量化来获取熊猫数据框列并将特定月份的所有天更改为一天,但是,该列似乎仍被解释为一个系列,而不是被迭代。谁能帮助我做错了什么?

我要更改的列是 ['Date_Time']。例如,如果条目是“2019-05-11 09:00:00”,我想将其更改为“2019-05-15 09:00:00”。

import pandas as pd
from datetime import datetime
from random import random

# Create a mini-dataframe to test on
df = pd.DataFrame(columns=['WindowID', 'Date_Time', 'Occlusion'])
dy = 11
for i in range(6):
    x = i+1
    hr = 9
    while hr < 18:
        z = random()
        y = datetime(year=2019, month=5, day=dy, hour=hr, minute=00, second=00)
        df = df.append({'WindowID': x, 'Date_Time': y, 'Occlusion': z}, ignore_index=True)
        hr += 2
    dy += 1

# Create a function for normalizing the day of the month
def normmonth(dt):
    print(dt.month)
    if dt.month == 5:
        rpday = 15
    elif dt.month == 10:
        rpday = 30
    dt2 = dt.replace(day=rpday)
    return dt2

df['Date_Time2'] = normmonth(df['Date_Time'])

这是错误:“AttributeError:'Series' 对象没有属性'month'”。

我还发现这是一篇关于迭代 pandas 数据帧的非常有用的文章

标签: pandasdataframeiterationvectorization

解决方案


推荐阅读