首页 > 解决方案 > 拆分列名并从列名中的数据创建新列

问题描述

我在熊猫数据框中有传感器数据,如下所示:

Timestamp           1014.temperature    1014.humidity   1015.temperature    1015.humidity   1016.temperature    1016.humidity
2017-10-01 00:00:00 11.396667           92.440806       10.513333      92.204295            11.040000            92.959605  

由每列中点之前的SensorID4 位数字给出。Timestamp索引数据。数据继续用于多个时间戳和 SensorID。

我可以做些什么来检索SensorID每列中的 以创建一个新列,以便我的数据框看起来像:

Timestamp            SensorID Temperature   Humidity
2017-10-01 00:00:00  1014     11.396667     92.440806
2017-10-01 00:00:00  1015     10.513333     92.204295
2017-10-01 00:00:00  1016     11.040000     92.959605

谢谢。

标签: pythonpandasdataframetime-series

解决方案


首先str.splitMultiIndex在列中,并通过DataFrame.stack第一级进行整形,最后DataFrame.reset_indexrename

#if Timestamp is column
#df = df.set_index('Timestamp')

df.columns = df.columns.str.split('.', expand=True)
df = df.stack(level=0).reset_index().rename(columns={'level_1':'SensorID'})
print (df)
             Timestamp SensorID   humidity  temperature
0  2017-10-01 00:00:00     1014  92.440806    11.396667
1  2017-10-01 00:00:00     1015  92.204295    10.513333
2  2017-10-01 00:00:00     1016  92.959605    11.040000

推荐阅读