我不是最好的,在日期的操作,但也許是這樣的:
import pandas as pd
from datetime import timedelta
df = pd.read_csv("hourmelt.csv", sep=r"\s+")
df = pd.melt(df, id_vars=["Date"])
df = df.rename(columns={'variable': 'hour'})
df['hour'] = df['hour'].apply(lambda x: int(x.lstrip('h'))-1)
combined = df.apply(lambda x:
pd.to_datetime(x['Date'], dayfirst=True) +
timedelta(hours=int(x['hour'])), axis=1)
df['Date'] = combined
del df['hour']
df = df.sort("Date")
一些解釋如下。
從
>>> import pandas as pd
>>> from datetime import datetime, timedelta
>>>
>>> df = pd.read_csv("hourmelt.csv", sep=r"\s+")
>>> df
Date h1 h2 h3 h4 h24
0 14.03.2013 60 50 52 49 73
1 14.04.2013 5 6 7 8 9
開始,我們可以使用pd.melt
,使每小時列合併到一列與價值:
>>> df = pd.melt(df, id_vars=["Date"])
>>> df = df.rename(columns={'variable': 'hour'})
>>> df
Date hour value
0 14.03.2013 h1 60
1 14.04.2013 h1 5
2 14.03.2013 h2 50
3 14.04.2013 h2 6
4 14.03.2013 h3 52
5 14.04.2013 h3 7
6 14.03.2013 h4 49
7 14.04.2013 h4 8
8 14.03.2013 h24 73
9 14.04.2013 h24 9
擺脫那些h
S的:
>>> df['hour'] = df['hour'].apply(lambda x: int(x.lstrip('h'))-1)
>>> df
Date hour value
0 14.03.2013 0 60
1 14.04.2013 0 5
2 14.03.2013 1 50
3 14.04.2013 1 6
4 14.03.2013 2 52
5 14.04.2013 2 7
6 14.03.2013 3 49
7 14.04.2013 3 8
8 14.03.2013 23 73
9 14.04.2013 23 9
合併兩列作爲日期:
>>> combined = df.apply(lambda x: pd.to_datetime(x['Date'], dayfirst=True) + timedelta(hours=int(x['hour'])), axis=1)
>>> combined
0 2013-03-14 00:00:00
1 2013-04-14 00:00:00
2 2013-03-14 01:00:00
3 2013-04-14 01:00:00
4 2013-03-14 02:00:00
5 2013-04-14 02:00:00
6 2013-03-14 03:00:00
7 2013-04-14 03:00:00
8 2013-03-14 23:00:00
9 2013-04-14 23:00:00
重新組裝和清理:
>>> df['Date'] = combined
>>> del df['hour']
>>> df = df.sort("Date")
>>> df
Date value
0 2013-03-14 00:00:00 60
2 2013-03-14 01:00:00 50
4 2013-03-14 02:00:00 52
6 2013-03-14 03:00:00 49
8 2013-03-14 23:00:00 73
1 2013-04-14 00:00:00 5
3 2013-04-14 01:00:00 6
5 2013-04-14 02:00:00 7
7 2013-04-14 03:00:00 8
9 2013-04-14 23:00:00 9
來源
2013-03-15 13:13:10
DSM
不錯的解決方案!你可以將'df ['hour']。apply(...)'和'combined = ...'行結合到'df ['Date'] + = df ['hour']。apply(lambda x: timedelta(小時= INT(x.lstrip( 'H')) - 1))'。 – unutbu 2013-03-15 13:28:06
偉大的解決方案。非常感謝。我剛剛設置日期作爲索引,它完美的作品。 > df = df.set_index('Date') – 2013-03-15 16:47:04