user3759978
user3759978

Reputation: 309

How to insert a string into a numpy list every nth index?

Let's say i have a list like this one:

b = np.array(['a','b','c','a','b','c','a','b','c','a','b','c'])

and i wanted to insert this character at every 17th position '\n':

np.insert(b,b[::16],'\n')

why do i get this error message and how would be a corect way to do this?

ValueError: invalid literal for int() with base 10: 'a'

Thank you very much

Upvotes: 4

Views: 1644

Answers (1)

akuiper
akuiper

Reputation: 215037

The second argument for np.insert should be the index to place the values, you can try:

n = 3
np.insert(b, range(n, len(b), n), "\n") 

# array(['a', 'b', 'c', '\n', 'a', 'b', 'c', '\n', 'a', 'b', 'c', '\n', 'a',
#        'b', 'c'], 
#       dtype='<U1')

Upvotes: 4

Related Questions