简体   繁体   中英

Reading .txt file columns into pandas data frame and creating new columns

I have a .txt file which looks like the following:

      156 2.87893e+06
      157 968759
      699 2.15891e+06
      700 44927.2
      1108 830338
      1156 70513.5
      1172 64263.2

The above file is an output file I am obtaining on running a c++ prog. I want this output file in pandas df.

I tried following code:

       df = pd.read_csv("output.txt", index_col=0)
       df

But here, columns from .txt file becomes one column in the df. I want the values in 2 columns separately, maybe with a column heading.

OR since its a text file, if they are not 2 different columns in .txt file, then each row has 2 values separated by a space. How can I get them in two different cols in pandas df ?

Also, I tried the following code:

        df = pd.read_csv("output.txt")
        df.iloc[:,(0)]

Now, here the very first row from the original text file doesn't appears at all, and again both the values appear in one column.

pandas.read_csv的默认分隔符是逗号,您需要将sep参数显式指定为空格才能读取空格分隔文件:

df = pd.read_csv("output.txt", sep = " ", index_col=0, header=None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM