0

I have the following list 'list1' of strings:

list1= ['mz', '-3956901.50', '-1310316.62', '-505251.812', '-6262072.50', '-0.781772032E+10-0.113921731E+11']

I want to convert columns 2 to the last column to a numpy array:

np.asarray(list[1:],dtype='float')

The problem is that I get a ValueError due to the last item in the list. How do I split the last item first into two strings (due to the space which is missing in the delimiter)?

2 Answers 2

1

You can do the following:

  1. Split the last value in the list by split with delimiter '-'
  2. Add the delimiter in case of a not empty string (split will also return empty strings)
  3. Remove the last value in the list and add the split string
list1= ['mz', '-3956901.50', '-1310316.62', '-505251.812', '-6262072.50', '-0.781772032E+10-0.113921731E+11']

delimeter = "-"
splited_string_with_delemeter =  [delimeter+splited_string for splited_string in list1[-1].split(delimeter) if splited_string]

list2 = list1[:-1] + splited_string_with_delemeter

Then you'll be able to create the NumPy array:

np.asarray(list2[1:],dtype='float')

The result is:

array([-3.95690150e+06, -1.31031662e+06, -5.05251812e+05, -6.26207250e+06,
       -7.81772032e+09, -1.13921731e+10])
Sign up to request clarification or add additional context in comments.

Comments

0

For the list1's last item, you can use eval() function to convert it to number, then your code will work:

list2 = np.asarray([eval(x) for x in list1[1:]],dtype='float')

the result is:

array([-3.95690150e+06, -1.31031662e+06, -5.05251812e+05, -6.26207250e+06,
       -1.92098934e+10])

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.