簡體   English   中英

如何使用pandas創建pivot_table,其中顯示的不是我用於索引的其他字段

[英]How can i create pivot_table with pandas, where displayed other fields than i use for index

我為python使用包“pandas”。 我有一個問題。 我有這樣的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   |

我希望按字段['first','last','datr']創建pivot_table,但顯示['first','last','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('first','last','datr','city'),groupby - 2('first','last')的列,4-2 = 2:

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

你可以用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'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM