赵雨轩 - 8 months ago 75

Python Question

I have a matrix created by the following code:

`import numpy as np`

table_vals = np.random.randn(4,4).round(4) * 100

and I've tried to convert numbers into percentages like this:

`>>> table_vals.astype(np.string_) + '%'`

TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32')

and like this:

`>>> np.str(table_vals) + '%'`

"[[ 137.08 120.31 -55.73 43.6 ]\n [ -94.35 -105.27 -23.31 59.16]\n [-132.9 12.04 -36.69 106.52]\n [ 126.11 -91.38 -29.16 -138.01]]%"

but all of them failed. So what should I do?

Answer

You can use the formatting as:

```
[["%.2f%%" % number for number in row] for row in table_vals]
```

If you want it as a numpy array, then wrap it in `np.array`

method so it becomes:

```
np.array([["%.2f%%" % number for number in row] for row in table_vals])
```

Source (Stackoverflow)