拆分列名称并根据列名称中的数据创建新列

Adr*_*rra 3 python time-series dataframe 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  
Run Code Online (Sandbox Code Playgroud)

SensorID是由4位数字在各列中的点之前给出。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
Run Code Online (Sandbox Code Playgroud)

谢谢。

jez*_*ael 5

首先str.split对于MultiIndex在列,并通过重塑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
Run Code Online (Sandbox Code Playgroud)