如何使用pandas创建pivot_table,其中显示的其他字段不是我用于索引

时间:2015-09-24 08:53:18

标签: python pandas data-analysis

我使用包" pandas"对于python。我有一个问题。 我有这样的DataFrame:

|  first  |  last  |  datr  |city|
|Zahir    |Petersen|22.11.15|9   |
|Zahir    |Petersen|22.11.15|2   |
|Mason    |Sellers |10.04.16|4   | 
|Gannon   |Cline   |29.10.15|2   |
|Craig    |Sampson |20.04.16|2   |
|Craig    |Sampson |20.04.16|4   |
|Cameron  |Mathis  |09.05.15|6   |
|Adam     |Hurley  |16.04.16|2   |
|Brock    |Vaughan |14.04.16|10  |
|Xanthus  |Murray  |30.03.15|6   |
|Xanthus  |Murray  |30.03.15|7   |
|Xanthus  |Murray  |30.03.15|4   |
|Palmer   |Caldwell|31.10.15|2   |

我希望按字段['首先','最后',' datr']创建pivot_table,但显示 ['首先','最后',' datr'' city']其中记录的数量为[' first' ;,'最后',' datr']不止一个,像这样:

|  first  |  last  |  datr  |city| 
|Zahir    |Petersen|22.11.15|9   | 2
|         |        |        |2   | 2
|Craig    |Sampson |20.04.16|2   | 2
|         |        |        |4   | 2
|Xanthus  |Murray  |30.03.15|6   | 3
|         |        |        |7   | 3
|         |        |        |4   | 3 

UPD。 如果我分组来自四个的三个字段,而不是

df['count'] = df.groupby(['first','last','datr']).transform('count') 

可行,但如果所有列的数量 - 列为" groupby" > 1 比此代码抛出错误。例如(所有列 - 4('第一个','最后',' datr',' city'),groupby的列 - 2 ('首先','最后'),4-2 = 2:

In [181]: df['count'] = df.groupby(['first','last']).transform('count') 
...
ValueError: Wrong number of items passed 2, placement implies 1

1 个答案:

答案 0 :(得分:3)

您可以使用groupby执行此操作。按三列(first,last和datr)分组,然后计算每组中元素的数量:

In [63]: df['count'] = df.groupby(['first', 'last', 'datr']).transform('count')

In [64]: df
Out[64]:
        first      last      datr  city  count
0   Zahir      Petersen  22.11.15     9      2
1   Zahir      Petersen  22.11.15     2      2
2   Mason      Sellers   10.04.16     4      1
3   Gannon     Cline     29.10.15     2      1
4   Craig      Sampson   20.04.16     2      2
5   Craig      Sampson   20.04.16     4      2
6   Cameron    Mathis    09.05.15     6      1
7   Adam       Hurley    16.04.16     2      1
8   Brock      Vaughan   14.04.16    10      1
9   Xanthus    Murray    30.03.15     6      3
10  Xanthus    Murray    30.03.15     7      3
11  Xanthus    Murray    30.03.15     4      3
12  Palmer     Caldwell  31.10.15     2      1

从那里,您可以过滤框架:

In [65]: df[df['count'] > 1]
Out[65]:
        first      last      datr  city  count
0   Zahir      Petersen  22.11.15     9      2
1   Zahir      Petersen  22.11.15     2      2
4   Craig      Sampson   20.04.16     2      2
5   Craig      Sampson   20.04.16     4      2
9   Xanthus    Murray    30.03.15     6      3
10  Xanthus    Murray    30.03.15     7      3
11  Xanthus    Murray    30.03.15     4      3

如果您希望这些列作为索引(如问题中的示例输出中所示):df.set_index(['first', 'last', 'datr'])