0

I am trying to order (sort) some data in csv file using python (panda) in specific order but i cant figure it out. I would really appreciate your help.

The csv file has like five columns, what I want to do is to show 4 of the columns as headers (master) and the fifth column as the (detail). for example: the header (master) flight-id, from(airport),to (airport),total_time and for the detail part it should show the passengers names for that specific flight

1 FRA  MAD  10HR

A

B

C

2 MAD FRA  11HR

G

F

H

K
BENY
  • 317,841
  • 20
  • 164
  • 234
s_am
  • 57
  • 1
  • 9

1 Answers1

0

The expectation of Pandas doing master-detail style data structures as well as having headers and rows of different structure will have to be adjusted a bit. Pandas works best when performing operations on tabular data along consistent axes, for example.

If you can provide an MVCE a better answer may be obtained.

From the looks of the desired output, a pandas multindex may be the best way to go.

import pandas as pd
import csv
from pandas.compat import StringIO

print(pd.__version__)

csvdata = StringIO("""A,B,C,D
FRA,MAD,10HR,A
FRA,MAD,10HR,B
FRA,MAD,10HR,C
MAD,FRA,11HR,G
MAD,FRA,11HR,F
MAD,FRA,11HR,H
MAD,FRA,11HR,K""")

df = pd.read_csv(csvdata, sep=",")
df.set_index(['A', 'B', 'C'], inplace=True)
print(df)

Produces

0.24.2
              D
A   B   C      
FRA MAD 10HR  A
        10HR  B
        10HR  C
MAD FRA 11HR  G
        11HR  F
        11HR  H
        11HR  K

Rich Andrews
  • 1,590
  • 8
  • 12