[Python] Import .dat file containing index, as pandas dataframe

Discussão em 'Python' iniciado por Stack, Janeiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I have a .dat file, containing column data separated by indices, for example here i show just 2 indices:

    # t= 400000
    1601 -0.207587E-02 0.454623E-03 0.193855E-02 0.996661E+00
    1602 -0.202550E-02 0.447789E-03 0.191164E-02 0.996661E+00
    1603 -0.197461E-02 0.440763E-03 0.188373E-02 0.996660E+00
    1604 -0.192326E-02 0.433553E-03 0.185483E-02 0.996660E+00
    1605 -0.187150E-02 0.426169E-03 0.182494E-02 0.996659E+00

    # t= 410000
    1601 -0.207587E-02 0.454623E-03 0.193855E-02 0.996661E+00
    1602 -0.202550E-02 0.447789E-03 0.191164E-02 0.996661E+00
    1603 -0.197461E-02 0.440763E-03 0.188373E-02 0.996660E+00
    1604 -0.192326E-02 0.433553E-03 0.185483E-02 0.996660E+00
    1605 -0.187150E-02 0.426169E-03 0.182494E-02 0.996659E+00


    I would like to import them as panda dataframes and give names at each column. Also, I want to keep the index information (probably in a new column). I have tried the following but it does not work

    import pandas as pd
    from io import StringIO
    df = pd.read_csv(StringIO(filename),
    sep="\t",
    skiprows=1,
    usecols=[0,1,2,3,4],
    names=['position','ux', 'uy', 'uz', 'rho'])

    print(df)


    It has multiple entries. Each index "t" corresponds to different times of a simulation output. And at each time I have the 5 columns. I want to save the .dat file in the following dataframe form

    t pos ux uy uz rho
    400000 1601 -0.207587E-02 0.454623E-03 0.193855E-02
    0.996661E+00
    400000 1602 -0.202550E-02 0.447789E-03 0.191164E-02
    0.996661E+00 ....
    410000 1603 -0.197461E-02 0.440763E-03 0.188373E-02
    0.996660E+00
    410000 1604 -0.192326E-02 0.433553E-03 0.185483E-02
    0.996660E+00
    410000 1605 -0.187150E-02 0.426169E-03 0.182494E-02
    0.996659E+00


    like merging everything together.

    Continue reading...

Compartilhe esta Página