【问题标题】:How do I convert a pandas pivot table to a dataframe如何将熊猫数据透视表转换为数据框
【发布时间】:2014-03-31 23:52:25
【问题描述】:

我想使用数据透视表来汇总数据集,然后能够像访问 DataFrame 一样访问数据透视表中的信息。

考虑一个分层数据集,其中包含在医院接受治疗的患者和位于区域内的医院:

import pandas as pd

example_data = {'patient' : ['p1','p2','p3','p4','p5','p6','p7','p8','p9','p10','p11','p12','p13','p14','p15','p16','p17','p18','p19','p20','p21','p22','p23','p24','p25','p26','p27','p28','p29','p30','p31','p32','p33','p34','p35','p36','p37','p38','p39','p40','p41','p42','p43','p44','p45','p46','p47','p48','p49','p50','p51','p52','p53','p54','p55','p56','p57','p58','p59','p60','p61','p62','p63'], 
                'hospital' : ['h1','h1','h1','h2','h2','h2','h2','h3','h3','h3','h3','h3','h4','h4','h4','h4','h4','h4','h5','h5','h5','h5','h5','h5','h5','h6','h6','h6','h6','h6','h6','h6','h6','h7','h7','h7','h7','h7','h7','h7','h7','h7','h8','h8','h8','h8','h8','h8','h8','h8','h8','h8','h9','h9','h9','h9','h9','h9','h9','h9','h9','h9','h9'], 
                'region' : ['r1','r1','r1','r1','r1','r1','r1','r1','r1','r1','r1','r1','r2','r2','r2','r2','r2','r2','r2','r2','r2','r2','r2','r2','r2','r2','r2','r2','r2','r2','r2','r2','r2','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3','r3'] }

example_dataframe = pd.DataFrame(example_data)

print example_dataframe

这会产生一个简单的输出,如下所示:

   hospital patient region
0        h1      p1     r1
1        h1      p2     r1
2        h1      p3     r1
3        h2      p4     r1
4        h2      p5     r1
5        h2      p6     r1
6        h2      p7     r1
7        h3      p8     r1
8        h3      p9     r1
9        h3     p10     r1
10       h3     p11     r1
11       h3     p12     r1
12       h4     p13     r2
13       h4     p14     r2
14       h4     p15     r2
15       h4     p16     r2
16       h4     p17     r2
etc.

现在我想用一个数据透视表来总结一下,简单地统计每家医院的病人数量:

example_pivot_table = pd.pivot_table(example_dataframe, values='patient', rows=['hospital','region'], aggfunc='count')

print example_pivot_table

这会产生以下输出:

hospital  region
h1        r1         3
h2        r1         4
h3        r1         5
h4        r2         6
h5        r2         7
h6        r2         8
h7        r3         9
h8        r3        10
h9        r3        11
Name: patient, dtype: int64

据我了解,这实际上是一个多索引系列。

如何使用这些数据找出 h7 医院所在的地区?如果hospitalregion 和患者计数数据是 DataFrame 中的单独列,那将很容易。但我认为医院和地区是指数。我已经尝试了很多东西,但无法让它发挥作用。

【问题讨论】:

  • 我试过 .reset_index(inplace=True) 但这只是产生了一条错误消息。但是,使用 .reset_index() 是一种享受!非常感谢您的快速响应。

标签: python pandas pivot-table


【解决方案1】:

您可以使用get_level_values 获取医院专栏。您可以传递级别的数量或级别的名称,即0hospital

然后你就可以得到你想要的:

In [38]: example_pivot_table[ example_pivot_table.index.get_level_values('hospital') == 'h7' ]
Out[38]: 
hospital  region
h7        r3        9
Name: patient, dtype: int64

更新

要获取区域,您可以这样做

example_pivot_table[ example_pivot_table.index.get_level_values('hospital') == 'h7' ]['regions']

【讨论】:

  • 谢谢waitingkuo。这不是我想要的,因为我希望能够获得 'r3' 位。但是,所概述的方法将来会非常有用,它也有助于我了解如何在 pandas 中操作数据。再次感谢。
【解决方案2】:

首先,这不是数据透视表作业,而是groupby 作业。

数据透视表用于在您未设置索引时重新调整数据(请参阅this doc article),stackunstack 用于在您设置索引时重新调整数据, 而groupby 用于聚合(这就是它)和split-apply-combine 操作。

以下是使用 groupby 获取患者人数的方法:

>>> patient_count = df.groupby(['hospital', 'region']).count()
>>> print patient_count
                 patient
hospital region         
h1       r1            3
h2       r1            4
h3       r1            5
h4       r2            6
h5       r2            7
h6       r2            8
h7       r3            9
h8       r3           10
h9       r3           11

要选择多索引中的某些行,我通常使用ix,如下所示:

>>> h7 = patient_count.ix['h7']
>>> print h7
        patient
region         
r3            9

现在你可以使用get_level_values

>>> h7.index.values[0]
'r3'

或者,如果您不想要多索引版本(而且,出于您的目的,您可能不想要)您可以这样做:

>>> patient_count = patient_count.reset_index()

这可以让您找到h7所在的地区医院如下:

>>> patient_count.region[patient_count.hospital == 'h7']
6    r3
Name: region, dtype: object

如果你只想要r3,你可以这样做:

>>> patient_count.region[patient_count.hospital == 'h7'].values[0]
'r3'

请注意,reset_index 不会就地发生,这使得它非常适合像这样的链接方法:

>>> patient_count.ix['h7'].reset_index().region[0]
'r3'

【讨论】:

  • 非常感谢您的回复。这很有帮助。但我不太明白数据透视表和分组依据之间的区别。什么时候应该使用它们?
  • @user1718097 我已更新答案以反映我尝试回答您的评论问题。
【解决方案3】:

这样就可以了:

levels = example_pivot_table.columns.levels
labels = example_pivot_table.columns.labels
example_pivot_table.columns = levels[1][labels[1]]
example_pivot_table.reset_index(inplace=True)
example_pivot_table

因此,在数据透视表中找到级别和标签,分配列名并在其中重置索引。最终结果应该是枢轴的结果数据框。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-01
    • 2018-03-09
    • 2019-04-24
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 2017-08-26
    相关资源
    最近更新 更多