3

I have this array:

z = np.array(['43', '65', '41', '47', '46', '73', '99', '52', '56', '23', '07',
       'C3', '49', '62', '54', 'A1', '88', '70', '42', 74.0, 20.0, 21.0,
       4, 62, 2, 3, 49, 79, '13', 'F4', 'A9', '20', '19', 19.0, 23.0,
       70.0, 83, 61, 80, 81, 66, 82, 63, '09', '06', 'F8'], dtype=object)

In this array, we have int, str and float in one array. I want to convert all of them into string but float values have to be integer and the values such as '07', '09', etc also turn into '7', '9'. The desire result I want is:

z = np.array(['43', '65', '41', '47', '46', '73', '99', '52', '56', '23', '7',
       'C3', '49', '62', '54', 'A1', '88', '70', '42', '74', '20', '21',
       '4', '62', '2', '3', '49', '79', '13', 'F4', 'A9', '20', '19', '19', '23',
       '70', '83', '61', '80', '81', '66', '82', '63', '9', '6', 'F8'], dtype=object)

I have tried this method

def col_convert(array):
    for i in range(len(array)):
        try:
            array[i] = str(int(array[i]))
        except:
            next
    return array   

However for 1 million elements, this solution are quite slow. Are there any way faster to handle this task?

5
  • Why do you use split('.')? Commented Jul 21, 2020 at 10:30
  • And why do you want a numpy array of strings as a result? Would it not be better to have an array of numbers? Commented Jul 21, 2020 at 10:32
  • your proposed solution removes strings. You do not need to check for type. Commented Jul 21, 2020 at 10:55
  • @mkrieger1 Ah because I want to score them as a string, they can be considered as area code in my company (the area code includes both number and string) Commented Jul 21, 2020 at 11:23
  • Write a little function that takes on element, determines the type, and applies the necessary conversion, and returns that string. Then just apply that to the whole array (or list) with a list comprehension. There isn't a whole-array numpy function that will handle all the cases as you want. For tasks like this an object dtype array is inferior to a list. Commented Jul 21, 2020 at 16:08

1 Answer 1

3

Try:

z1 = np.array([str(i).split('.')[0] for i in z])

UPDATE: Per OP's edit to remove leading zeros:

z1 = np.array([str(i).lstrip('0').split('.')[0] for i in z])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you sir, I have editted my post. I also want to convert the values which starts with 0 such as '07', '09', '06' into '7', '9', '6'
@Long_NgV Please find the edit on my post to cover 0s as well. Thank you.

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.