2016-07-27 11 views
2

Was ist der effizienteste Weg, von einem 0/1 Pandas/numpy Datenrahmen von dieser Form gehen ::Python Pandas von 0/1 Datenrahmen zu einer itemset Liste

>>> dd 
{'a': {0: 1, 1: 0, 2: 1, 3: 0, 4: 1, 5: 1}, 
'b': {0: 1, 1: 1, 2: 0, 3: 0, 4: 1, 5: 1}, 
'c': {0: 0, 1: 1, 2: 1, 3: 0, 4: 1, 5: 1}, 
'd': {0: 0, 1: 1, 2: 1, 3: 1, 4: 0, 5: 1}, 
'e': {0: 0, 1: 0, 2: 1, 3: 0, 4: 0, 5: 0}} 
>>> df = pd.DataFrame(dd) 
>>> df 
    a b c d e 
0 1 1 0 0 0 
1 0 1 1 1 0 
2 1 0 1 1 1 
3 0 0 0 1 0 
4 1 1 1 0 0 
5 1 1 1 1 0 
>>> 

Zu einer itemset Liste der Liste? ::

itemset = [['a', 'b'], 
      ['b', 'c', 'd'], 
      ['a', 'c', 'd', 'e'], 
      ['d'], 
      ['a', 'b', 'c'], 
      ['a', 'b', 'c', 'd']] 

df.shape ~ (1e6, 500)

+0

Bezug zu http://stackoverflow.com/q/38604963/3313834 – user3313834

Antwort

2

können Sie zunächst mehr von spalten~~POS=TRUNC von mul und konvertieren DataFrame zu numpy array von values:

print (df.mul(df.columns.to_series()).values) 
[['a' 'b' '' '' ''] 
['' 'b' 'c' 'd' ''] 
['a' '' 'c' 'd' 'e'] 
['' '' '' 'd' ''] 
['a' 'b' 'c' '' ''] 
['a' 'b' 'c' 'd' '']] 

Entfernen leerer String durch verschachtelte Liste Verständnis:

print ([[y for y in x if y != ''] for x in df.mul(df.columns.to_series()).values]) 
[['a', 'b'], 
['b', 'c', 'd'], 
['a', 'c', 'd', 'e'], 
['d'], 
['a', 'b', 'c'], 
['a', 'b', 'c', 'd']] 
+0

Ich denke, dass die Antwort von Divakar besser skaliert ist, oder? – user3313834

+0

numpy Lösungen sind in der Regel kompliziert und offensichtlich besser skalieren. Also probier es aus. – jezrael

0

Einfache Liste comprehesion:

itemset = [[df.columns.values[j] # the output based on the following logic: 
    for j in range(0, len(df.iloc[i])) 
     if df.iloc[i][j] == 1] 
    for i in range(0, len(df.index))] 

print (itemset) 

Gibt das Ergebnis:

$ python test.py 
[['a', 'b'], ['b', 'c', 'd'], ['a', 'c', 'd', 'e'], ['d'], ['a', 'b', 'c'], ['a', 'b', 'c', 'd']] 

Hier ist ein weiteres Format: Füge das zu t hinzu Das Ende des Listenverständnisses.

print ('[', end='') 
for i in range(0, len(itemset)): 
    if i == len(itemset) - 1: 
     print (itemset[i], end='') 
    else: 
     print (itemset[i], end=',\n ') 
print (']') 

Ausgang:

$ python test.py 
[['a', 'b'], 
['b', 'c', 'd'], 
['a', 'c', 'd', 'e'], 
['d'], 
['a', 'b', 'c'], 
['a', 'b', 'c', 'd']] 
1

Hier ist ein NumPy basiert vektorisiert Ansatz eine Liste von Arrays als Ausgabe zu erhalten -

In [47]: df 
Out[47]: 
    a b c d e 
0 1 1 0 0 0 
1 0 1 1 1 0 
2 1 0 1 1 1 
3 0 0 0 1 0 
4 1 1 1 0 0 
5 1 1 1 1 0 

In [48]: cols = df.columns.values.astype(str) 

In [49]: R,C = np.where(df.values==1) 

In [50]: np.split(cols[C],np.unique(R,return_index=True)[1])[1:] 
Out[50]: 
[array(['a', 'b'], 
     dtype='|S1'), array(['b', 'c', 'd'], 
     dtype='|S1'), array(['a', 'c', 'd', 'e'], 
     dtype='|S1'), array(['d'], 
     dtype='|S1'), array(['a', 'b', 'c'], 
     dtype='|S1'), array(['a', 'b', 'c', 'd'], 
     dtype='|S1')] 
Verwandte Themen