print numpy array for copy and paste

Viewed 479

Sometimes, I would like to print a numpy array just to copy it from the command line into somewhere else. The standard __repr__ is close, but missing the commas:

import numpy as np

a = np.random.rand(5, 2)
print(a)
[[0.66585668 0.5793219 ]
 [0.28048686 0.11019737]
 [0.41359919 0.69354774]
 [0.02062253 0.85507001]
 [0.05443759 0.51366551]]

Any hints?

1 Answers

Assuming your desired output is the following:

[
    [0.5838947919313026, 0.05795999970550392],
    [0.9737053546477267, 0.7160755144818707],
    [0.17361370495727824, 0.09849691691484186], 
    [0.863423476768234, 0.7065666761268419],
    [0.18712559034118503, 0.21525050659592326]
]

You can use a list comprehension and the list constructor to do this:

import numpy as np
a = np.random.rand(5, 2)
print([list(i) for i in a])
Related