【问题标题】:Split column names and create new column from data in column name拆分列名并从列名中的数据创建新列
【发布时间】:2019-08-07 06:28:21
【问题描述】:

我在 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。

我可以做些什么来检索每列中的 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

谢谢。

【问题讨论】:

    标签: python pandas dataframe time-series


    【解决方案1】:

    第一个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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 2021-08-02
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      • 1970-01-01
      • 2022-08-10
      相关资源
      最近更新 更多