将时间列 Headers 与 DataFrame Pandas 中行中的相应日期连接起来

Concatenating Time Column Headers with Corresponding dates in rows in a DataFrame Pandas

所以我基本上有这个数据集,其中我将一天中的时间以 15 分钟为间隔(12:15、12:30、12:45 等)作为我的列 headers.每行都有一个从 2010 年到 2020 年的日期,我想要做的基本上是将时间(列 headers)与行相匹配。

print (df)
        Date     0:15     0:30     0:45     1:00     1:15     1:30     1:45  
0  01May2010  2.98298  2.30478  2.57654  2.44110  2.25174  2.20100  2.15370   
1  02May2010  2.31606  2.20325  2.12952  2.09236  2.04150  2.08978  1.01500   
2  03May2010  2.07710  2.13000  2.07249  2.05315  2.08925  1.94481  1.85551   

以下是我希望行的样子

01-May-2010 0:15
01-May-2010 0:30
01-May-2010 0:45
... till 
01-May-2010 11:45
01-May-2010 12:00
02-May-2010 12:15
etc etc

所以基本上我只想要 2 列而不是 100 列。一个是值,另一个是日期+时间。

我该怎么做?我知道我需要使用 pandas 但我真的很困惑在这里做什么。

使用DataFrame.melt with to_datetime with joined columns with DataFrame.pop使用删除列variable:

df = df.melt('Date', value_name='val')
df['Date'] = pd.to_datetime(df['Date'] + ' ' + df.pop('variable'), format='%d%b%Y %H:%M')

df = df.sort_values('Date', ignore_index=True)
print (df.head(10))
                 Date      val
0 2010-05-01 00:15:00  2.98298
1 2010-05-01 00:30:00  2.30478
2 2010-05-01 00:45:00  2.57654
3 2010-05-01 01:00:00  2.44110
4 2010-05-01 01:15:00  2.25174
5 2010-05-01 01:30:00  2.20100
6 2010-05-01 01:45:00  2.15370
7 2010-05-02 00:15:00  2.31606
8 2010-05-02 00:30:00  2.20325
9 2010-05-02 00:45:00  2.12952

没有转换为日期时间的解决方案 DataFrame.set_index and DataFrame.stack:

df = df.set_index('Date').stack()
df.index = df.index.map(' '.join)
df = df.rename_axis('date').reset_index(name='val')

print (df.head(10))
             date      val
0  01May2010 0:15  2.98298
1  01May2010 0:30  2.30478
2  01May2010 0:45  2.57654
3  01May2010 1:00  2.44110
4  01May2010 1:15  2.25174
5  01May2010 1:30  2.20100
6  01May2010 1:45  2.15370
7  02May2010 0:15  2.31606
8  02May2010 0:30  2.20325
9  02May2010 0:45  2.12952