pandas从日期属性中提取年月日

在数据挖掘过程中,日期属性是非数值属性, 不能直接输入到模型,将日期属性拆分成年、月和日是必要的。

date属性是object类型的, 通过取单元格可以发现它是字符串类型,这样很容易提取年、月、日

《pandas从日期属性中提取年月日》

《pandas从日期属性中提取年月日》

将日期属性拆分成年、月、日, 代码如下:

def DateSplit(df, col):
    """
    split the object of '2010-01-02' into year(2010), month(1) and day(2).
    :param df:  to operate data (type:DataFrame)
    :param col: column label of date object (type:str)
    :return: converted date (type: DataFrame)
    """
    year, month, day = [], [], []
    data = df.loc[:, col].values
    df = df.drop([col], axis=1)
    
    for i in range(data.shape[0]):
        year.append(int(data[i][:4]))
        month.append(int(data[i][5:7]))
        day.append(int(data[i][8:]))
    date = pd.DataFrame({'year': year, 'month': month, 'day': day})
    result = pd.concat([date, df], axis=1)
    return result


pm25_train = pd.read_csv("./datasets_PM25/pm25_train.csv")
data= DateSplit(df=pm25_train,col='date')
data.head(10)

 

《pandas从日期属性中提取年月日》

    原文作者:潘旭阳
    原文地址: https://blog.csdn.net/Joseph__Lagrange/article/details/90550681
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞