【问题标题】:Pandas: reshaping and multi-indexPandas:重塑和多索引
【发布时间】:2016-05-05 14:25:57
【问题描述】:

我有一个包含这些列的 pandas 数据框:

  • itemid
  • 15/01/2015 状态
  • 15/01/2015 地点
  • 15/02/2015 状态
  • 15/02/2015 地点

这两件事我该怎么做?

  1. 创建多索引列,其中第一个索引是月份,第二个索引是我正在跟踪的指标(状态、位置)
  2. 堆叠列,使表格看起来像这样:

+--------+-----------+----------+--------+--+
| itemid |  mymonth  | location | status |  |
+--------+-----------+----------+--------+--+
| A      | 15/1/2015 | North    | Good   |  |
| A      | 15/2/2015 | South    | Bad    |  |
+--------+-----------+----------+--------+--+

从如下所示的输入开始:

+--------+-------------------+---------------------+-------------------+---------------------+
| itemid | 15/01/2015 status | 15/01/2015 location | 15/02/2015 status | 15/02/2015 location |
+--------+-------------------+---------------------+-------------------+---------------------+
| A      | Good              | North               | Bad               | South               |
+--------+-------------------+---------------------+-------------------+---------------------+

哪些(输入)可以通过以下方式重新创建:

import pandas as pd
df=pd.DataFrame()
df['itemid']=['A']
df['15/01/2015 status'] = ['Good']
df['15/01/2015 location'] = ['North']
df['15/02/2015 status'] = ['Bad']
df['15/02/2015 location'] = ['South']

我一直在考虑如何使用melt,但我不太确定它是否可以在这种情况下工作。

【问题讨论】:

  • 您可以添加可以创建所需输出的输入 DataFrame 示例吗?

标签: python pandas dataframe reshape


【解决方案1】:

您可以将stacksplit 一起使用,最后将pivot_tablerename_axis 一起使用(pandas 0.18.0 中的新功能):

df1 = df.set_index('itemid').stack().reset_index()
df1.columns = ['itemid','mymonth', 'd']

df1[['mymonth','c']] = df1.mymonth.str.split('\s+').apply(pd.Series)
print df1
  itemid     mymonth      d         c
0      A  15/01/2015   Good    status
1      A  15/01/2015  North  location
2      A  15/02/2015    Bad    status
3      A  15/02/2015  South  location

print df1.pivot_table(index=['itemid', 'mymonth'], columns='c', values='d', aggfunc='first')
        .reset_index()
        .rename_axis(None, axis=1)

  itemid     mymonth location status
0      A  15/01/2015    North   Good
1      A  15/02/2015    South    Bad

编辑:

我认为如果通过first 进行聚合,您有时会丢失数据,因为您只带来第一个值(如果在创建新索引的列中存在重复),而其他值会丢失。

所以如果按字符串聚合,你可以使用join。数据不会丢失,仅由, 连接和分隔:

print df1.pivot_table(index=['itemid', 'mymonth'], columns='c', values='d',aggfunc=', '.join)
         .reset_index()
         .rename_axis(None, axis=1)

【讨论】:

  • 你是明星!非常感谢!
  • 感谢您的接受。我添加了下一个解决方案 - 我很害怕,因为您可能会丢失数据。请检查一下,如果有不清楚的地方,我可以尝试更好地解释。
  • 谢谢。在特定情况下,我正在研究这不是问题,幸运的是,因为数据不会重复。
猜你喜欢
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 2019-12-07
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
相关资源
最近更新 更多