简体   繁体   English

将.txt文件列读入pandas数据框并创建新列

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

I have a .txt file which looks like the following: 我有一个.txt文件,如下所示:

      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. 上面的文件是我在运行c ++ prog时获得的输出文件。 I want this output file in pandas df. 我想在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. 但是在这里,.txt文件中的列成为df中的一列。 I want the values in 2 columns separately, maybe with a column heading. 我想分别在2列中的值,可能有列标题。

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. 或者因为它是一个文本文件,如果它们不是.txt文件中的2个不同的列,那么每行有2个以空格分隔的值。 How can I get them in two different cols in pandas df ? 如何在pandas df中将它们放入两个不同的cols中?

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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