2

What would be a numpy function that goes through array a and then appends the endswidth to the end of each string in the a array.

Code:

a = np.array(["BTC", "ETH", "AUD", "DOGE"])
endswidth = "USD"

Expected output:

[BTCUSD, ETHUSD, AUDUSD, DOGE] 

2 Answers 2

2

You can use np.core.defchararray.add:

a = np.array(["BTC", "ETH", "AUD", "DOGE"])
endswidth = "USD"

print(np.core.defchararray.add(a, endswidth))

Prints:

['BTCUSD' 'ETHUSD' 'AUDUSD' 'DOGEUSD']

EDIT: To replace a string:

print(np.core.defchararray.replace(a, "USD", ""))

As @hpulj stated in the comments, the short form:

np.char.add(...) 
np.char.replace(...)
Sign up to request clarification or add additional context in comments.

2 Comments

if I wanted to remove "USD" instead of the .add what would I use because I tried subtract and remove dont work.
np.char.add for short.
1

perhaps this brute force approach will help

np.array([item+endswidth for item in a])

1 Comment

For string operations this is just as good as the np.char.add. numpy does not implement its own fast string methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.