0

How to convert a set to an array?

I tried:

import numpy as np

mySet = {1,2,3,4,5}

myRandomArray = np.asarray(mySet, dtype=int, order="C")

print(myRandomArray)

Output

return array(a, dtype, copy=False, order=order)

TypeError: int() argument must be a string, a bytes-like object or a number, not 'set'

Where am I making the mistake?

faruk13
  • 1,276
  • 1
  • 16
  • 23
user366312
  • 16,949
  • 65
  • 235
  • 452
  • The set already contains integers, just do `np.asarray(mySet)` – yatu Jul 18 '19 at 08:09
  • 1
    @yatu, *The set already contains strings* - what does it even mean? – user366312 Jul 18 '19 at 08:10
  • @yatu, `np.asarray(mySet, dtype=set, order="C")` ? – user366312 Jul 18 '19 at 08:13
  • `dtype : data-type, optional The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to ‘upcast’ the array. For downcasting, use the .astype(t) method.` – yatu Jul 18 '19 at 08:14
  • Possible duplicate of https://stackoverflow.com/questions/8466014/how-to-convert-a-python-set-to-a-numpy-array/56967649#56967649 – tstanisl Jul 18 '19 at 09:09

2 Answers2

1
myset = {1,2,3,4,5}
np.array(list(myset))
Abhishek Kumar
  • 768
  • 1
  • 8
  • 23
  • 2
    While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. It will be helpful for future users as well. – Sangam Belose Jul 18 '19 at 08:47
  • 1
    I suspect there is something or someone that automatically flags answers that are pure code. Add a few superfluous words, and no one will complain! – hpaulj Jul 18 '19 at 16:42
0

The array factory doesn't handle non sequence iterables too well. fromiter is better here:

a = set(range(5)) 
np.fromiter(a,int,len(a))
# array([0, 1, 2, 3, 4]) 
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
  • This answer might rely on a specific Python version, since [before 3.6/3.7 sets do not have a fixed iterating order](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6). But admittedly the problem was lurking in the OP's request as well. – Leporello Jul 18 '19 at 08:38
  • @Leporello I do not know the exact relationship between the set and dict implementations, but unlike dicts sets do not remember insertion order. Anyway, your remark probably applies to any answer that doesn't actually sort the set which I find too expensive to do unless it's required. – Paul Panzer Jul 18 '19 at 08:48
  • I thought sets were "ordered" as well now, but you're probably right since [the docs](https://docs.python.org/3/library/stdtypes.html#set) say nothing of the sort. – Leporello Jul 18 '19 at 08:53