2014-07-01 69 views
1

所以我有一個數據幀,看起來像下面這樣:使用Pandas groupby將每一行分成多個組?

In [5]: import pandas as pd, numpy as np 
np.random.seed(seed=43525) 
descriptors = 'abcdefghi' 
df = pd.DataFrame([{'Value':np.random.randint(0,100), 
         'Group':descriptors[np.random.randint(0, len(descriptors)): 
              np.random.randint(0, len(descriptors))]} for i in range(0,10)]) 
print(df) 

    Group Value 
0   4 
1 abc  37 
2 efgh  99 
3  a  67 
4   37 
5   52 
6   46 
7  b  41 
8  d  17 
9   36 

的每個字符在描述符列表應成爲它自己的組(連同空組)。我如何執行groupby來完成此任務?

因此,組'a'將包含索引1和3,組'b'將包含索引1和7等。這是一個相當非標準的使用groupby的方法(如果它可以完全用它來完成)所以我不知道如何繼續。

+0

將你想要做的事情分組後,你想要做什麼與總和/計數等。 – EdChum

+0

你只是想要不同的組的行索引? – EdChum

+0

行索引就足夠了,我相信因爲那麼我可以做df [df.isin(indices)]來獲取組 – tlnagy

回答

1

關於Edchum答案的建築我想出了以下內容。這種結構類似於一個groupby對象也認爲:

indices = {} 
for val in np.unique(''.join(df.Group.values)): 
    indices[val] = df[df.Group.str.contains(val)] 
print(indices) 

提供下述嚴重格式化,但正確答案:

{'a': Group Value 
1 abc  37 
3  a  67, 'c': Group Value 
1 abc  37, 'b': Group Value 
1 abc  37 
7  b  41, 'e': Group Value 
2 efgh  99, 'd': Group Value 
8  d  17, 'g': Group Value 
2 efgh  99, 'f': Group Value 
2 efgh  99, 'h': Group Value 
2 efgh  99} 
+0

雖然有一個問題。我不包括屬於任何類別的行。我正在努力解決這個問題。 – tlnagy

1

這聽起來像你真正想要的是一個MultiIndexgroupby會爲您提供獨特的羣組 - 基本上您在Group列中擁有的內容,但MultiIndex會讓您更接近您所期望的內容。現在

例如,

descriptors = 'abcdefghi' 
df = pd.DataFrame([{'Value':np.random.randint(0,100), 
         'Group':descriptors[np.random.randint(0, len(descriptors)): 
              np.random.randint(0, len(descriptors))]} for i in range(0,10)]) 

groups = df.Group.map(lambda x : tuple(desc if desc in x else '-' for desc in descriptors)) 
df.index = pd.MultiIndex.from_tuples(groups.values, names=list(descriptors)) 
df 

Out[4]: 
        Group Value 
a b c d e f g h i    
- - - - - - - - -   4 
a b c - - - - - - abc  37 
- - - - e f g h - efgh  99 
a - - - - - - - -  a  67 
- - - - - - - - -   37 
       -   52 
       -   46 
    b - - - - - - -  b  41 
    - - d - - - - -  d  17 
     - - - - - -   36 

,您可以使用df.xsdf.ix選擇數據。例如,如果你想與「A」和他們的「C」的所有組,您可以使用

df.xs(('a', 'c'), level=('a', 'c')) 
Out[5]: 
       Group Value 
b d e f g h i    
b - - - - - - abc  37 

同樣,你可以選擇包含「B」的所有組

df.xs('b', level='b') 
Out[7]: 
       Group Value 
a c d e f g h i    
a c - - - - - - abc  37 
- - - - - - - -  b  41 

選擇非分組的行,你可以使用

df.sort_index(inplace=True) #index must be sorted 
df.ix[('-',) * len(descriptors)] 
Out[10]: 
        Group Value 
a b c d e f g h i    
- - - - - - - - -   4 
       -   37 
       -   52 
       -   46 
       -   36 

注:我用「 - 」作爲填充字符,但是這是不是真的有必要。