Home > Back-end >  Python pandas csv multirow values into arrays
Python pandas csv multirow values into arrays

Time:01-14

I have a csv that has values spread over multiple rows like this (real data has about 70 columns)

id | name | alias
 1 |  Amy | Potato
   |      | Fortress
 2 | Bill | Gyroscope
...

Now I want to import this into a dataframe. I can do it with row-by-row processing but I was wandering if there is some smarter built-in way.

CodePudding user response:

If your csv file looks like:

id,name,alias
1,Amy,Potato
,,Fortress
2,Bill,Gyroscope

You can use ffill

df = pd.read_csv('data.csv', dtype=str).ffill()
print(df)

# Output
  id  name      alias
0  1   Amy     Potato
1  1   Amy   Fortress
2  2  Bill  Gyroscope

CodePudding user response:

If your data is look like below, as you describe:

id | name | alias
 1 |  Amy | Potato
   |      | Fortress
 2 | Bill | Gyroscope

Supoose this data saved in data.txt file, then you can simply

df = pd.read_csv('data.txt', sep='|')
  •  Tags:  
  • Related