How can I add characters before and after each ID in this array?

Viewed 69

I scraped and collected IDs from the Japanese horse racing information site. The array of ID is stored as a NumPy array. How can I add characters before and after each ID in this array?

import numpy as np

a = np.array([2019104896, 2016102929, 2018105085]) 
print(a) # [2019104896 2016102929 2018105085]
print(type(a)) # <class 'numpy.ndarray'>
b = a.astype(str)
c = "\n".join(b) # new line 
with open('horse_id.txt', 'w') as f: # make a text file
    f.write(c)

By executing the above code, I got the following text file.

horse_id.text
2019104896
2016102929
2018105085

I'd like to add characters before and after each ID like this:

'https://db.netkeiba.com/horse/' + ID + '/'

What I want to create is the following text file

horse_id.txt
https://db.netkeiba.com/horse/2019104896/
https://db.netkeiba.com/horse/2016102929/
https://db.netkeiba.com/horse/2018105085/

How can i achieve that?

2 Answers

Try this:

import numpy as np

a = np.array([2019104896, 2016102929, 2018105085]) 
with open('horse_id.txt', 'w') as f: # make a text file
    f.write('horse_id.txt\n')
    for n in a:
        f.write(f'https://db.netkeiba.com/horse/{n}/\n')

Output: (in 'horse_id.txt')

horse_id.txt
https://db.netkeiba.com/horse/2019104896/
https://db.netkeiba.com/horse/2016102929/
https://db.netkeiba.com/horse/2018105085/

If you're willing to use Pandas, then simply and without (explicit) loops:

import numpy as np
import pandas as pd

a = np.array([2019104896, 2016102929, 2018105085]) 
b = 'https://db.netkeiba.com/horse/' + pd.Series(a).astype(str) + '/'
b.to_csv('horse_id.txt', index=False, header=None)

Check:

$ cat horse_id.txt
https://db.netkeiba.com/horse/2019104896/
https://db.netkeiba.com/horse/2016102929/
https://db.netkeiba.com/horse/2018105085/

and also:

>>> b
0    https://db.netkeiba.com/horse/2019104896/
1    https://db.netkeiba.com/horse/2016102929/
2    https://db.netkeiba.com/horse/2018105085/
dtype: object
Related