I am trying to manipulate an array and perform operations. My input is an array
a= [['f' '0' '1' '0' '1' '0']
['o' '0' '0' '1' '0' '0']
['o' '0' '1' '0' '1' '1']
['!b' '1' '0' '1' '0' '0']
['a' '0' '0' '1' '0' '0']
['r' '0' '1' '0' '1' '1']]
If I take the first row, my output should just be the columns in which 1 is present. Similarly, I do for each row and get output. So my output should be an array.
output = [['f' '1' '1'
'o' '0' '0'
'o' '1' '1'
'!b' '0' '0'
'a' '0' '0'
'r' '1' '1' ]
['f' '0'
'o' '1'
'o' '0'
'!b' '1'
'a' '1'
'r' '0' ]
['f' '1' '1' '0'
'o' '0' '0' '0'
'o' '1' '1' '1'
'!b' '0' '0' '0'
'a' '0' '0' '0'
'r' '1' '1' '1']
['f' '0' '0'
'o' '0' '1'
'o' '0' '0'
'!b' '1' '1'
'a' '0' '1'
'r' '0' '0' ]
['f' '0'
'o' '1'
'o' '0'
'!b' '1'
'a' '1'
'r' '0' ]
['f' '1' '1' '0'
'o' '0' '0' '0'
'o' '1' '1' '1'
'!b' '0' '0' '0'
'a' '0' '0' '0'
'r' '1' '1' '1']]
Here's my Code
output = []
for i in a:
for j in i:
if j == 1:
output = a[0:]
output.append([n][j]) for n in len(i)
else:
pass
1 Answer 1
For each row, produce a matrix that has only the columns that have a '1' in this row.
import numpy as np
a = np.array([['f', '0', '1', '0', '1', '0'],
['o', '0', '0', '1', '0', '0'],
['o', '0', '1', '0', '1', '1'],
['!b', '1', '0', '1', '0', '0'],
['a', '0', '0', '1', '0', '0'],
['r', '0', '1', '0', '1', '1']])
l = []
for r in a:
l.append(a[:, [i for i, c in enumerate(r) if i == 0 or c == '1']])
print l
This works but perhaps someone more familiar with numpy might be able to do better.
Produces:
[array([['f', '1', '1'],
['o', '0', '0'],
['o', '1', '1'],
['!b', '0', '0'],
['a', '0', '0'],
['r', '1', '1']],
dtype='|S2'), array([['f', '0'],
['o', '1'],
['o', '0'],
['!b', '1'],
['a', '1'],
['r', '0']],
dtype='|S2'), array([['f', '1', '1', '0'],
['o', '0', '0', '0'],
['o', '1', '1', '1'],
['!b', '0', '0', '0'],
['a', '0', '0', '0'],
['r', '1', '1', '1']],
dtype='|S2'), array([['f', '0', '0'],
['o', '0', '1'],
['o', '0', '0'],
['!b', '1', '1'],
['a', '0', '1'],
['r', '0', '0']],
dtype='|S2'), array([['f', '0'],
['o', '1'],
['o', '0'],
['!b', '1'],
['a', '1'],
['r', '0']],
dtype='|S2'), array([['f', '1', '1', '0'],
['o', '0', '0', '0'],
['o', '1', '1', '1'],
['!b', '0', '0', '0'],
['a', '0', '0', '0'],
['r', '1', '1', '1']],
dtype='|S2')]
answered Nov 23, 2015 at 9:49
Dan D.
75.1k15 gold badges111 silver badges129 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
1in this row.