拆分列名,并从列名中的数据创建新列



我在pandas数据框架中具有传感器数据,看起来像:

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  

SensorID由每个列中的点之前的4位数字给出。Timestamp索引数据。数据继续进行多个时间戳和传感器。

我该怎么做才能在每列中检索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

谢谢。

列中的MultiIndex第一个str.split,并通过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

最新更新