1

I am very much a Python beginner using Thonny and Python 3.7.7. I have strings of values that I want to convert to integers and put in a numpy array. A typical string:

print(temp)
05:01:00016043:00002F4F:00002F53:00004231:000050AA:00003ACE:00005C44:00003D3B:000064BC

temp = temp.split(":")
print(temp)

['05', '01', '00016043', '00002F4F', '00002F53', '00004231', '000050AA', '00003ACE', '00005C44', '00003D3B', '000064BC']

I want to efficiently turn this list of strings describing hexadecimal numbers into integers and put them into an numpy array (with the emphasis on efficiently!).

a = np.array([11], dtype=int)

Any suggestions? Thanks

0

2 Answers 2

2

How about a nice and tidy one-line list comprehension? For a string s:

np.array([int(hexa, base=16) for hexa in s.split(sep=":")])

This may look complicated, but the output of s.split(sep=":") is a list of string hexadecimals. Passing each one of them (each hexa) into int with base=16 converts them, as you'd like.

Sign up to request clarification or add additional context in comments.

Comments

1

Apply function which converts x to int(x, 16) to every element in L

import pandas as pd
import numpy as np

L = ['05', '01', '00016043', '00002F4F', '00002F53', '00004231', '000050AA', '00003ACE', '00005C44', '00003D3B', '000064BC']
output = pd.Series(L).apply(lambda x:int(x, 16)).values
print(output)

output is

[    5     1 90179 12111 12115 16945 20650 15054 23620 15675 25788]

Comments

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.