2016-04-26 200 views
2

我對熊貓有問題。我有一個包含三列的數據框:'id1','id2','amount'。從另一個創建一個數據幀(使用數據透視表)

由此,我想創建另一個數據幀,其索引是'id1',其中的列是'id2',並且這些單元格包含相應的'數量'。

我們去一個例子:

import pandas as pd 
df = pd.DataFrame([['first_person','first_item',10],['first_person','second_item',6],['second_person','first_item',18],['second_person','second_item',36]],columns = ['id1','id2','amount']) 

這將產生:

 id1    id2    amount 
0 first_person  first_item  10 
1 first_person  second_item  6 
2 second_person first_item  18 
3 second_person second_item  36 

而從這個我想創建第二個數據幀是:

    first_item second_item 
first_person  10   6 
second_person 18   36 

當然,在發佈之前我已經研究了一段時間,但是我爲此設法做了一個雙重'for循環'...... Whic我的數據幀的大小無法計算。你會知道如何以更pythonic的方式做到這一點? (這顯然是遠遠比更有效「的」循環!)

回答

4

我認爲你可以使用pivotrename_axis(新中pandas0.18.0):

print df 
      id1   id2 amount 
0 first_person first_item  10 
1 first_person second_item  6 
2 second_person first_item  18 
3 second_person second_item  36 

print df.pivot(index='id1', columns='id2', values='amount') 
     .rename_axis(None) 
     .rename_axis(None, axis=1) 

       first_item second_item 
first_person   10   6 
second_person   18   36 
+0

這似乎完全適合我的需要!執行重命名索引問題。事實上,'.rename_axis(None)'方法返回以下錯誤:'必須通過索引來重命名'(如果它很重要,我在Python 2.7下)。 – ysearka

+0

「pandas」的版本是什麼? 'print pd.show_versions()' – jezrael

+0

0.17.1這解釋了爲什麼rename_axis不起作用。 – ysearka