簡體   English   中英

DataFrame:datetime列轉int型

[英]DataFrame: datetime column to int type

我正在使用 DataFrame,並從其他兩個列創建了一個新的日期時間列('time_diff')。 我現在需要將新的“time_diff”列轉換為一個 int 列,計算天數。

我已經嘗試過.astype(int),但沒有成功。

這是我的代碼:

# Preprocessing start and end dates
from datetime import datetime

train_plus = train_full.copy()

# Replace all last_event_DI 'unk' with corresponding start_time_DI
for i in range(len(train_plus)): # Makes a range from 0 to #-1, this is needed to loop over the length
    if (train_plus['last_event_DI'][i] == 'unk'):
        train_plus['last_event_DI'][i] = train_plus['start_time_DI'][i]

# Last interaction - start date = length of interaction (time_diff)
train_plus['time_diff'] = train_plus['last_event_DI'].apply(pd.to_datetime) - train_plus['start_time_DI'].apply(pd.to_datetime)

# I need the 'time_diff' column to become an int column
# CONVERSION CODE HERE

train_plus   

下面是代碼和 dataframe 的截圖:

我的代碼截圖和DataFrame

謝謝!

我認為你這樣做:

train_plus['time_diff'] = train_plus['time_diff'].days

回答。 簡單的解決方案:

# Replace all time_diff time_deltas with int
for i in range(len(train_plus)): # Makes a range from 0 to #-1, this is needed to loop over the length
    train_plus['time_diff'][i] = train_plus['time_diff'][i].days

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM