Apy - 7 months ago 38

Python Question

I have a NumPy array as follows:

`supp = np.array([['A', '5', '0'], ['B', '3', '0'], ['C', '4', '0'], ['D', '1', '0'], ['E', '2', '0']])`

Now, I want to update the row[2] as row[1]/6.

I'm using..

`for row in supp:`

row[2] = row[1].astype(int) / 6

But row[2] seems to remain unaffected..

`>>> supp`

array([['A', '5', '0'],

['B', '3', '0'],

['C', '4', '0'],

['D', '1', '0'],

['E', '2', '0']],

dtype='<U1')

I'm using Python 3.5.2 and NumPy 1.11.1.

Any help is appreciated. Thanks in advance

Answer

The problem is that an `np.array`

has only one type which is automatically assumed to be strings `supp.dtype == '|S1'`

since your input contains only strings of length `1`

. So numpy will automatically convert your updated inputs to strings, `0`

in your case. Force it to be of generic type `object`

and then it will be able to have both strings and ints or floats or anything else:

```
supp = np.array([['A', '5', '0'], ['B', '3', '0'], ['C', '4', '0'], ['D', '1', '0'], ['E', '2', '0']])
supp = supp.astype(object)
for row in supp:
row[2] = int(row[1]) / 6
```

alternatively you can also use the `dtype`

`'|Sn'`

with larger value of `n`

:

```
supp = np.array([['A', '5', '0'], ['B', '3', '0'], ['C', '4', '0'], ['D', '1', '0'], ['E', '2', '0']])
supp = supp.astype('|S5')
for row in supp:
row[2] = int(row[1]) / 6
```

and in this case you are still having only strings.