python - Pandas: reshape 和多索引

标签 python pandas dataframe reshape

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

  • 项目编号
  • 2015 年 1 月 15 日状态
  • 2015 年 1 月 15 日地点
  • 2015 年 2 月 15 日状态
  • 2015 年 2 月 15 日地点
  • 等等

我该如何做这两件事?

  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,但我不太确定它是否适用于这种情况。

最佳答案

您可以使用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)

关于python - Pandas: reshape 和多索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37053186/

相关文章:

python - 使用 Python/Pandas 处理嵌套在 JSON 中的 JSON

python - 计算数据帧切片的统计信息

r - 如何删除某些句子后面的文字?

python - 使用Selenium和python检查是否存在任何警报

python - 向 Django 2.1 管理站点添加忘记密码功能

python - pd.Timestamp 与 np.datetime64 : are they interchangeable for selected uses?

python pandas : Check if dataframe's column value is in another dataframe's column, 然后计数并列出它

python - Django ChoiceField 编辑后保存 None 值?

python - 根据另一列中的值创建重复的递增序列

python - 使用羽化格式包出错