Read multiple *.txt files into Pandas Dataframe with filename as column header

后端 未结 2 1617
太阳男子
太阳男子 2021-01-07 01:21

I am trying to import a set of *.txt files. I need to import the files into successive columns of a Pandas DataFrame in Python.

Requirements and Background informati

相关标签:
2条回答
  • 2021-01-07 01:51

    You can read them into multiple dataframes and concat them together afterwards. Suppose you have two of those files, containing the data shown.

    In [6]:
    filelist = ['val1.txt', 'val2.txt']
    print pd.concat([pd.read_csv(item, names=[item[:-4]]) for item in filelist], axis=1)
        val1  val2
    0     16    16
    1     54    54
    2   -314  -314
    3      1     1
    4     15    15
    5      4     4
    6    153   153
    7     86    86
    8      4     4
    9     64    64
    10   373   373
    11     3     3
    12   434   434
    13    31    31
    14    93    93
    15    53    53
    16   873   873
    17    43    43
    18    11    11
    19   533   533
    20    46    46
    
    0 讨论(0)
  • 2021-01-07 02:10

    You're very close. ijk is the filename already, you don't need to access the list:

    # Step 3: Build up DataFrame: df = pd.DataFrame() for ijk in filelist: frame = pd.read_csv(ijk) df = df.append(frame) print df

    In the future, please provide working code exactly as is. You import from pandas import * yet then refer to pandas as pd, implying the import import pandas as pd.

    You also want to be careful with variable names. files is actually a single file path, and filelist and filesList have no discernible difference from the variable name. It also seems like a bad idea to keep personal documents in your python directory.

    0 讨论(0)
提交回复
热议问题