【问题标题】:Using python pandas dataframe to rearrange continuous data log使用 python pandas 数据框重新排列连续的数据日志
【发布时间】:2018-02-14 14:54:57
【问题描述】:

作为 pandas 的新手,我正在努力解决数据排列问题。

我从 Pandas 数据框中的日志文件中获得了大量数据,其结构如下:

day   user   measure1   measure2   ...
1     u1     xxxxx      yyyyy      ...
1     u2     xxxxx      yyyyy      ...
1     u3     xxxxx      yyyyy      ...
2     u2     xxxxx      yyyyy      ...
2     u4     xxxxx      yyyyy      ...
2     u3     xxxxx      yyyyy      ...
3     u1     xxxxx      yyyyy      ...
3     u3     xxxxx      yyyyy      ...
...   ...    ...        ...        ...

因此,并非每个用户每天都会出现,而数据既不是按天排序,也不是按用户排序。但是,如果出现条目,则具有所有措施。

现在我需要重新排列这些数据以获得每个度量的“每个用户”与“每天”的 2D 表,并用零填充空白,例如

For measure1:                      For measure2:
      u1     u2     u3     u4            u1     u2     u3     u4
1  xxxxx  xxxxx  xxxxx      0      1  yyyyy  yyyyy  yyyyy      0  
2      0  xxxxx  xxxxx  xxxxx      2      0  yyyyy  yyyyy  yyyyy  
3  xxxxx      0  xxxxx      0      3  yyyyy      0  yyyyy      0  

如何在 python3 中使用 pandas 来做到这一点? 我也对替代解决方案持开放态度,例如使用 numpy 而不是 pandas。

到目前为止,我设法提取了数据集中所有出现的用户和日期的数组,但不知道如何巧妙地分配测量数据。

感谢您在此问题上提供的任何帮助。

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    你需要set_indexunstack

    df.set_index(['day','user']).measure1.unstack(fill_value=0)
    Out[6]: 
    user     u1     u2     u3     u4
    day                             
    1     xxxxx  xxxxx  xxxxx      0
    2         0  xxxxx  xxxxx  xxxxx
    3     xxxxx      0  xxxxx      0
    df.set_index(['day','user']).measure2.unstack(fill_value=0)
    Out[7]: 
    user     u1     u2     u3     u4
    day                             
    1     yyyyy  yyyyy  yyyyy      0
    2         0  yyyyy  yyyyy  yyyyy
    3     yyyyy      0  yyyyy      0
    

    【讨论】:

    • 天才,太棒了。我拼凑了一个工作方法,以用户名作为列来构建一个新的 Dataframe,并循环数天来填充它,结果证明这很慢。你的单线是完美的。谢谢!
    • @MadMad yw :-) 快乐编码
    【解决方案2】:

    您似乎想要一个多索引数据框(index1:day,index2:measure)

    棘手的部分是您可能需要在这些操作之前转置数据帧。看看这个问题的答案,它看起来与你的相似Constructing 3D Pandas DataFrame

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2013-01-12
      • 2018-10-03
      • 1970-01-01
      • 2019-06-18
      • 1970-01-01
      • 2017-08-12
      • 2020-10-02
      • 1970-01-01
      • 2020-08-16
      相关资源
      最近更新 更多