Home > Software design >  Python: separate rows of arrays into columns in a dataframe
Python: separate rows of arrays into columns in a dataframe

Time:03-10

I have a csv file that contains one column and many rows like this format,

[[118 4 3 -169.0 246]]

How can I separate each number in a column?

The final result should be a data frame like this,

 Id   number  userId  location  area 
 118   4       3      -169.0    246



 

CodePudding user response:

If you have a string [[118 4 3 -169.0 246]], you can parse it into a list of floats like this

s = "[[118 4 3 -169.0 246]]"
assert s[1] == "["
assert s[-1] == "]"

s = s[2:-2]
nums = [float(v) for v in s.split(" ")]
print(nums)  # [118.0, 4.0, 3.0, -169.0, 246.0]

Then you can just parse every line of the file like this, create a list of list of numbers and create a DataFrame from there.

  • Related