python - 将时间列标题与 DataFrame Pandas 中行中的相应日期连接起来

标签 python python-3.x pandas dataframe multiple-columns

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

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.meltto_datetimeDataFrame.pop 连接的列使用和删除列变量:

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 转换为日期时间的解决方案和 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

关于python - 将时间列标题与 DataFrame Pandas 中行中的相应日期连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66816983/

相关文章:

python - 读取两行,程序需要输出每行数字匹配的位置

Python - 抓取网页以获取仅在滚动后出现的信息

python - 如何根据条件更改python数据框中的值(即列表)?

python - 何时使用反向内置而不是列表切片

python - 将列表列表构建为 csv/Excel 的列和行

python - 有条件删除 Pandas 中的重复条目

python - 如何对称排序相关矩阵?

python-3.x - 在 python3 中通过套接字发送 .mp4 文件

python - 如何根据另一个数据帧中的(日期)值过滤数据帧

python-3.x - python : SettingWithCopyWarning when trying to set value to True based on condition