【问题标题】:python pandas, transform data set, move rows into columns [duplicate]python pandas,转换数据集,将行移动到列中[重复]
【发布时间】:2020-02-09 02:19:29
【问题描述】:

有一个 csv 数据框,其中包含每小时间隔的属性及其值。并非每小时都会列出所有属性。它看起来像这样:

time                    attribute value
2019.10.11. 10:00:00    A           10
2019.10.11. 10:00:00    B           20
2019.10.11. 10:00:00    C           10
2019.10.11. 10:00:00    D           13
2019.10.11. 10:00:00    E           12
2019.10.11. 11:00:00    A           11
2019.10.11. 11:00:00    D           8
2019.10.11. 11:00:00    E           17
2019.10.11. 12:00:00    A           13
2019.10.11. 12:00:00    B           24
2019.10.11. 12:00:00    C           11
2019.10.11. 12:00:00    E           17

我想将其转换为每小时有一行,并且属性名称应与其值一起作为列。如果一个属性没有列出,那么它应该有一个零值或者也可以留空等......熊猫是否提供了一种合并、连接或连接或其他任何方法来自动执行此操作,还是我必须手动实现它?

我需要以下格式的数据集:

time                    A   B   C   D   E
2019.10.11. 10:00:00    10  20  10  13  12
2019.10.11. 11:00:00    11  0   0   8   17
2019.10.11. 12:00:00    13  24  11  0   17

感谢您的阅读!

【问题讨论】:

  • df.pivot_table('value', 'time', 'attribute', fill_value=0)
  • 非常感谢,成功了!

标签: python pandas join merge concatenation


【解决方案1】:

使用DataFrame.pivot_table:

df=df.pivot_table(columns='attribute',index='time' ,values ='value',fill_value=0)
print(df)

attribute              A   B   C   D   E
time                                   
2019.10.11. 10:00:00  10  20  10  13  12
2019.10.11. 11:00:00  11   0   0   8  17
2019.10.11. 12:00:00  13  24  11   0  17

【讨论】:

    【解决方案2】:

    你可以使用unstack + fillna:

    df = pd.DataFrame(data=data, columns=['time', 'attribute', 'value'])
    print(df.set_index(['time', 'attribute']).unstack(level=-1).fillna(0))
    

    输出

                         value                        
    attribute                A     B     C     D     E
    time                                              
    2019.10.11. 10:00:00  10.0  20.0  10.0  13.0  12.0
    2019.10.11. 11:00:00  11.0   0.0   0.0   8.0  17.0
    2019.10.11. 12:00:00  13.0  24.0  11.0   0.0  17.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-22
      • 2023-03-26
      • 2022-12-17
      • 2022-01-16
      • 2014-09-08
      • 2021-06-27
      • 2020-09-16
      • 2018-02-26
      相关资源
      最近更新 更多