[英]Pandas table re-shape | creating datetime column with hours
我正在嘗試用熊貓重塑一張桌子。 一年中每天有365行的日期列。 每小時24列,每個值24列,對應當天的小時。 我正在嘗試使用day + hour(每天24行)和具有相應值的列創建列。 這是一個當前的頭():
Date | hour1 | value1 | hour2 | value2 ... hour24 | value 24
2016-01-01 | 1 | 4100 | 2 | 3500 | 24 | 5200
Here is the desired format:
Date | value
2016-01-01 01 | 4100
2016-01-01 02 | 3500
....
2016-01-01 24 | 5200
我已經嘗試過熔化和旋轉,但無法獲得分類日+小時列。
您需要lreshape
通過dict
,然后加入hour
小號轉化為to_timedelta
和最后刪除列A
由drop
,如有必要sort_values
通過Date
列:
print (df)
Date hour1 value1 hour2 value2 hour24 value24
0 2016-01-01 1 4100 2 3500 24 5200
1 2016-01-02 1 3000 2 3700 24 7200
a = [col for col in df.columns if col.startswith('hour')]
b = [col for col in df.columns if col.startswith('value')]
df = pd.lreshape(df, {'A' : a, 'B' : b})
df['Date'] = pd.to_datetime(df['Date']) + pd.to_timedelta(df['A'], unit='h')
df = df.drop('A', axis=1).sort_values('Date')
print (df)
Date B
0 2016-01-01 01:00:00 4100
2 2016-01-01 02:00:00 3500
4 2016-01-02 00:00:00 5200
1 2016-01-02 01:00:00 3000
3 2016-01-02 02:00:00 3700
5 2016-01-03 00:00:00 7200
另一個解決方案是通過str.extract
創建MultiIndex.from_arrays
通過str.extract
重新DataFrame.stack
:
df = df.set_index('Date')
mux = df.columns.to_series().str.extract('([A-Za-z]+)(\d+)', expand=True)
df.columns = pd.MultiIndex.from_arrays([mux[0], mux[1]], names=('a','b'))
df = df.stack(1).reset_index()
df['Date'] = pd.to_datetime(df['Date']) + pd.to_timedelta(df['hour'], unit='h')
df = df.drop(['b', 'hour'], axis=1).rename_axis(None, axis=1)
print (df)
Date value
0 2016-01-01 01:00:00 4100
1 2016-01-01 02:00:00 3500
2 2016-01-02 00:00:00 5200
3 2016-01-02 01:00:00 3000
4 2016-01-02 02:00:00 3700
5 2016-01-03 00:00:00 7200
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.