Reputation: 3029
I have a numpy array of top 2 labels:
n = [['20011' '20048']
['20011' '20048']
['20011' '20048']
['20011' '20048']]
I want to get them in the reverse order:
[['20048' '20011']
['20048' '20011']
['20048' '20011']]
How can I do so while keeping the format the same?
Code till now:
n = model1.classes_[order[:,-5:]]
print(n)
r = [p[::-1] for p in n]
print(r)
Output:
[array(['20048', '20011'],
dtype='|S5'), array(['20048', '20011'],
dtype='|S5'), array(['20048', '20011'],
dtype='|S5'), array(['20048', '20011'],
dtype='|S5')]
Need to try getting rid of the dtypes
and keeping only the reversed array.
Upvotes: 3
Views: 2060
Reputation: 3989
Being a big fan of list comprehensions, I approached similar to Cleb, but with a reverse method from the list class instead using the list_name[::-1]
approach.
l1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
[l1[i].reverse() for i in range(len(l1))]
yields ...
[[3, 2, 1], [6, 5, 4], [10, 9, 8, 7]]
The key is to not set the comprehension equal to anything.
Upvotes: 0
Reputation: 26017
l = [['a', 'b', 'c'], ['d', 'e', 'f']]
Then a simple list comprehension like this
[li[::-1] for li in l]
gives you the desired output:
[['c', 'b', 'a'], ['f', 'e', 'd']]
EDIT:
As you changed your question:
Let's say you now have an array of arrays:
import numpy as np
l2 = np.array([np.array(['a', 'b', 'c']), np.array(['d', 'e', 'f'])])
Then you can do the following to get rid of the dtypes
:
map(list, l2[:, ::-1])
which gives you:
[['c', 'b', 'a'], ['f', 'e', 'd']]
But from your question it is still hard to tell what exact output format you want.
Upvotes: 2
Reputation: 180481
Your lists seem be missing commas so you actually have one string per list but you can do it inplace with list.reverse
if you want to modify the original sublists:
for sub in lists:
sub.reverse()
You actually have a numpy array so presuming it is in the correct format you can:
In [50]: arr
Out[50]:
array([['20015', '20013', '20044', '20001', '20002'],
['20002', '20015', '20001', '20013', '20070']],
dtype='|S5')
In [51]: arr[:,::-1]
Out[51]:
array([['20002', '20001', '20044', '20013', '20015'],
['20070', '20013', '20001', '20015', '20002']],
dtype='|S5')
To save to a file something like:
In [57]: arr[:,::-1].tofile("out.txt",sep=",")
In [58]: cat out.txt
20002,20001,20044,20013,20015,20070,20013,20001,20015,20002
If you want one row per line savetxt:
In [94]: np.savetxt("out.txt",arr[:,::-1],fmt="%s")
In [95]: cat out.txt
20002 20001 20044 20013 20015
20070 20013 20001 20015 20002
Upvotes: 5