2016-07-06 39 views
0

我想跨多個列過濾創建唯一值組合的數據幀的值。任何幫助,將不勝感激。通過跨多個列進行過濾來創建來自唯一值對的數據幀

這裏是我的代碼失敗(因爲數據幀DF):

dd = defaultdict(dict) #create blank default dictionary 
values_col1 = df.col1.unique() #get the unique values from column 1 of df 
for i in values_col1: 
    dd[i] = df[(df['col1']==i)] #for each unique value create a sorted df and put in in a dictionary 
    values_col2 = dd[i].col2.unique() #get the unique values from column2 of df 
    for m in values_col2: 
     dd[i][m] = dd[i][(dd[i]['col2']==m)] #for each unique column2 create a sub dictionary 

當我運行它,我得到一個非常長的錯誤消息。我不會在這裏插入了整個事情,但這裏是它的一些:

C:\Anaconda3\lib\site-packages\pandas\indexes\base.py in get_loc(self, key, method, tolerance) 1944 try: -> 1945 return self._engine.get_loc(key) 1946 except KeyError:

...

ValueError: Wrong number of items passed 6, placement implies 1

+0

瞭解numpy排列。 – Merlin

回答

2

使用熊貓groupby功能來提取唯一索引和數據框您的相應行。

import pandas as pd 
from collections import defaultdict 

df = pd.DataFrame({'col1': ['A']*4 + ['B']*4, 
        'col2': [0,1]*4, 
        'col3': np.arange(8), 
        'col4': np.arange(10, 18)}) 

dd = defaultdict(dict) 
grouped = df.groupby(['col1', 'col2']) 
for (c1, c2), g in grouped: 
    dd[c1][c2] = g 

這是生成的df

col1 col2 col3 col4 
0 A  0  0 10 
1 A  1  1 11 
2 A  0  2 12 
3 A  1  3 13 
4 B  0  4 14 
5 B  1  5 15 
6 B  0  6 16 
7 B  1  7 17 

,這是提取dd(當然,dict(dd)真的)

{'B': {0: col1 col2 col3 col4 
      4 B  0  4 14 
      6 B  0  6 16, 
     1: col1 col2 col3 col4 
      5 B  1  5 15 
      7 B  1  7 17}, 
'A': {0: col1 col2 col3 col4 
      0 A  0  0 10 
      2 A  0  2 12, 
     1: col1 col2 col3 col4 
      1 A  1  1 11 
      3 A  1  3 13}} 

(我不知道爲了什麼你的使用情況這是,但你最好不要將groupby對象解析爲字典)。

+0

感謝Alberto,你是如何在上面的代碼中創建「分組」的? – sparrow

+0

對不起,忘了複製該行。編輯。 –

+0

感謝您的優雅解決方案! – sparrow

相關問題