0

So i opened a dataset and in short it looked something like this:

list1= ['Adrian,20,5,2000,green', 'Steve,15,6,1997,blue', ...]
trial = np.array(list1)

when i tried to print(trial[0][0]) to get Adrian, i only got the A.

So i figured i should make everything that has a comma after it an independent element, please help me get the output to be:

(['Adrian', 20, 5, 2000, 'green'], ['steve', 15, 6, 1997, 'blue'], ...)

where print(trial[0]) will give: ['Adrian', 20, 5, 2000, 'green']

and print(trial[0][0]) will give: Adrian

1
  • It looks like your data comes from a CSV that was read incorrectly. Instead of trying to fix the data after reading it incorrectly, consider to read it correctly in the first place. If that is so, you might want to edit your question to show the data and how it is read. Commented Jun 1, 2021 at 15:40

1 Answer 1

1

Just use the split function with a comma as the parameter like this:-

list2= ['Adrian,20,5,2000,green', 'Steve,15,6,1997,blue']
list1= []
for i in list2:
    a = i.split(',')
    list1 += [a]
trial = numpy.array(list1)
print(trial[0][0])

This will return Adrian. You will still have to typecast the numbers to integer though, but that's easy to work around.

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

4 Comments

can you please offer an example?
@AdryanZiegler, you're welcome. Again, keep in mind that the numbers in the list are still currently strings, and if you are going to perform operations on them, you need to make sure that they are integers first.
yes i noticed. is there a way to check using if statement in the loop whether the string can be converted to an integer and if so change it to that integer, else skip to the next element? something like for item in list1: for element in item: if int(element) == true: element = int(element) or maybe add it to another empty list, what do you think? and thanks a lot again i truly appreciate it !!!
@AdryanZiegler use "String_number".isnumeric() , it will return true if its a number

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.