這是我的問題。
我有一個從 .xlsx 檔案匯入的資料框。它包含一列日期,但問題是它沒有顯示為日期時間。
例如,在第一行中,它是日期(格式:DD//MM/YYYY(型別 str),接下來的 24 行是小時(格式:xh(h 表示小時,x 介于 0 和 23 之間)) . 這樣重復了三年。
我想轉換此列,以便單元格是格式為 YY-MM-DD HH:MM:SS 的日期時間。
首先,我創建了一個包含小時數的資料框 df2:
indexNames = df1[df1['Hour'].str.contains('/')].index
df2= df1.drop(indexNames)
我將其轉換為日期時間格式 HH:MM
# Conserving the number
new = df2["Hour"].str.split("h", n = 1, expand = True)
new["new_Hour"]= new[0]
# Dropping old Name columns
df2.drop(columns = ["Hour"], inplace = True)
# Transforming in datetime format
df2['new_Hour'] = pd.to_datetime(df2['new_Hour'], format="%H")
df2['new_Hour'] = df2['new_Hour'].astype(str)
nouv = df2['new_Hour'].str.split(' ', n=1, expand = True)
df2["Hour"]= nouv[1]
df2.drop(columns = ["new_Hour"], inplace = True)
然后,我創建了第二個具有日期的資料框,并為相應的年、月和日添加了單獨的列:
df3= df1.loc[df1['Hour'].str.contains('/')].copy()
df3['Hour'] = pd.to_datetime(df3['Hour'], format="%d/%m/%Y")
df3['year'] = df3['Hour'].dt.year
df3['month'] = df3['Hour'].dt.month
df3['day'] = df3['Hour'].dt.day
我的問題來了
df3 索引在 0 處分層,每行取 25。這意味著 df3.index[0] = 0, df3.index[1] = 25, df3.index[2] = 50 等等
df2 索引從 1 開始,更一般地,缺少 df3 的索引。
我想將df3的相應日期添加到df2的相應時間。
在重置了 ddf2 和 df3 的索引后,我嘗試了:
df4 = df2.copy()
df4['year'] = 2019
df4= df4.reset_index(drop = True)
for i in range(len(df3)-1):
df4['year'].iloc[df3.index[i]:df3.index[i 1]] = df3['year'][i]
但是我遇到了復制問題,并且可能也出現了索引問題。
希望你能幫助我,謝謝。
uj5u.com熱心網友回復:
您可能想以一種更簡潔的方式開始創建日期時間列?例如喜歡(對不起,評論太長了......)
import pandas as pd
# dummy sample...
df = pd.DataFrame({'Hour': ["10/12/2013", "0", "1", "3",
"11/12/2013", "0", "1", "3"]})
# make a date column, forward-fill the dates
df['Datetime'] = pd.to_datetime(df['Hour'], format="%d/%m/%Y", errors='coerce').fillna(method="ffill")
# now we can add the hour
df['Datetime'] = df['Datetime'] pd.to_timedelta(pd.to_numeric(df['Hour'], errors='coerce'), unit='h')
# and optionally drop nans in the Datetime column, i.e. where we had dates initially
df = df[df["Datetime"].notna()].reset_index(drop=True)
df
Hour Datetime
0 0 2013-12-10 00:00:00
1 1 2013-12-10 01:00:00
2 3 2013-12-10 03:00:00
3 0 2013-12-11 00:00:00
4 1 2013-12-11 01:00:00
5 3 2013-12-11 03:00:00
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/493411.html
