【问题标题】:Reshape Long Format Multivalue Dataframes with Pandas用 Pandas 重塑长格式多值数据框
【发布时间】:2023-03-07 10:38:01
【问题描述】:

我想转:

DateTime                     ColumnName        Min      Avg      Max                                                                                      
2012-10-14 11:29:23.810000   Percent_Used       24       24       24
2012-10-14 11:29:23.810000   Current_Count  254503   254503   254503
2012-10-14 11:29:23.810000   Max           1048576  1048576  1048576
2012-10-14 11:34:23.813000   Percent_Used       24       24       24
2012-10-14 11:34:23.813000   Current_Count  254116   254116   254116
2012-10-14 11:34:23.813000   Max           1048576  1048576  1048576

进入一个数据帧,其中 DateTimes 是唯一的(索引)并且列是:

DataTime、Percent_Used_Min、Percent_Used_Avg、Percent_Used_Max、Current_Count_Min、Current_Count_Avg、Current_Count_Max、Max_Min、Max_Avg、Max_Max

基本上,我想在不涉及分层索引或堆叠数据帧的情况下模拟 R 的熔化/铸造。我似乎无法准确地使用 stack/unstack、melt 或 pivot/pivot_table 进行上述操作——有没有好的方法来做到这一点?

作为一个例子,在 R 中它会是这样的:

dynamic_melt = melt(dynamic, id = c("DateTime", "ColumnName"))
recast = data.frame(cast(dynamic_melt, DateTime ~ ...))

上述数据将是可变的(即 ColumnName 的值并不总是相同的,它们可能或多或少,并且名称不同)。

【问题讨论】:

  • 如果一个值只有“Avg”列,我可以得到我想要的:'.pivot('DateTime', 'ColumnName', 'Avg')'。但由于有多个值,我无法想出获得“平面”版本的方法。

标签: python pivot pandas reshape


【解决方案1】:

pandas.core.reshape中有一个melt

In [52]: melted = reshape.melt(df, id_vars=['DateTime', 'ColumnName'])

In [53]: melted.set_index(['DateTime', 'ColumnName', 'variable']).value.unstack([1, 2])
Out[53]: 
ColumnName                  Percent_Used  Current_Count      Max  Percent_Used  Current_Count      Max  Percent_Used  Current_Count      Max
variable                             Min            Min      Min           Avg            Avg      Avg           Max            Max      Max
DateTime                                                                                                                                    
2012-10-14 11:29:23.810000            24         254503  1048576            24         254503  1048576            24         254503  1048576
2012-10-14 11:34:23.813000            24         254116  1048576            24         254116  1048576            24         254116  1048576

这些列最终成为一个 MultiIndex,但如果这对您来说是一个交易破坏者,只需将名称连接起来并使其成为常规索引。

【讨论】:

  • 您如何连接名称,这就是我感到困惑的地方(“基本上,我想模仿 R 的熔化/铸造而不进入分层索引或堆叠数据帧” - 所以已经意识到这一点,我感到困惑的是如何将其转换为具有连接列名的平面结构。
  • result.columns = ['_'.join(x) for x in result.columns]
  • 仍然不了解如何使用 thta result.columns 获得所需的结果:-/
  • 假设result 是答案的输出。所以数据是你想要的形状,但列有 2 个级别,对吗?当您遍历列时,每个元素都是一个元组(例如,('Percent_Used', 'Min')),所以我之前的评论将导致扁平的单级索引。
  • 啊,这很好用。不知何故,在我的 ipython 会话中,我弄乱了您的示例,这导致了混乱。 Yay for ipython notebook -- 将开始使用它 -- 让事情变得更容易:-)
猜你喜欢
  • 2018-07-25
  • 2018-05-08
  • 2012-12-10
  • 2015-10-08
  • 1970-01-01
  • 2021-03-16
  • 2017-05-05
  • 1970-01-01
  • 2020-04-19
相关资源
最近更新 更多