2016-07-27 3 views
2
НИКАКИХ гарантий

Что является наиболее эффективным способом перейти от 0/1 панд/Numpy dataframe этой формы ::питона панд от 0/1 dataframe к списку

>>> 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 
>>> 

К списку НИКАКИХ гарантий списка? ::

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

df.shape ~ (1e6, 500)

+0

Связанных с http://stackoverflow.com/q/38604963/3313834 – user3313834

ответ

2

Вы можете первым множественным по именам столбцов по mul и конвертировать DataFrame в numpy array по 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' '']] 

Удалить пустую строку вложенным списком осмыслению:

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

Я думаю, что разница в Дивакаре лучше, не так ли? – user3313834

+0

решения numpy обычно сложны и, очевидно, лучше масштабируются. Так что попробуйте. – jezrael

0

Простой список 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) 

дает результат:

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

Вот другой формат: Добавьте это к t он заканчивает ваше понимание списка.

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 (']') 

Выход:

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

Вот Векторизованный подход, основанный NumPy, чтобы получить список массивов в качестве выходных -

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')] 
Смежные вопросы