【问题标题】:how to merge multiple dataframes inside one file, python如何在一个文件中合并多个数据框,python
【发布时间】:2017-06-23 10:35:24
【问题描述】:

在我的代码中,我收到了这样的结果:

A B C
1 1 1
A B C
2 2 2
A B C
3 3 3

我需要将这些列(数据框)合并到一个大数据框 喜欢

 A B C
 1 1 1
 2 2 2
 3 3 3

要合并来自不同文件的数据框,就像pd.merge(df1,df2) 一样容易,但是当数据框在一个文件中时如何做到这一点? 感谢您的建议!

编辑: 为了接收我的数据,我将数据集中的行转换为数据帧,并且我在一个输出中接收到每一行的每个数据集。 我的代码:

def coordinates():
    with open('file.txt') as file:
        for lines in file:
            lines =StringIO(lines[35:61]) #i need only those fields in each line
            abc=pd.read_csv(lines,sep=' ',header=None)
            abc.columns=['A', 'B', 'C','D','E','F']
            print abc

coordinates()

编辑2: 来自 s_vishnu 的建议仅适用于具有相同多个标题的已准备文件。但在我的情况下,我为文件生成了多个 DataFrame,并且标题后的每一行都有 0 值。它有很多数据框,每个只有一行。

编辑3: 在我的file.txt 中,我有很多行,大约有 80 个字母,如下所示:

AAA S S SSDAS ASDJAI A 234 33 43 234 2342999 2.31 22 33 SSS S D W2UUQ Q231WQ A 222 11 23 123 1231299 2.31 22 11

从那一行我只需要部分信息,这就是为什么我用lines =StringIO(lines[35:61]) 来获取这些信息。在这个例子中,我需要字母 [30:55] 并使用columns=['A', 'B', 'C','D','E','F'] with sep=' ' 创建数据框

【问题讨论】:

标签: python dataframe merge


【解决方案1】:

my_test.csv:

A, B, C
1, 1 ,1
A, B, C
2, 2, 2
A, B, C
3, 3, 3

使用列表切片

import pandas as pd
df = pd.read_csv("my_test.csv")
df=df[::2]
print(df)

输出:

   A    B   C
0  1   1    1
2  2    2   2
4  3    3   3

df=df[::2] 这是高级列表切片。其中df[::2] 中的 2 表示从 0 开始递增 2 步。

注意索引值。它们也以 2 为步长。即 0,2,4,.. 更改索引只需执行此操作即可。

import pandas as pd
df = pd.read_csv("my_test.csv")
df=df[::2]

df.index = range(len(df['A']))
print(df)

输出:

   A    B   C
0  1   1    1
1  2    2   2
2  3    3   3

所以你会得到你想要的值。

【讨论】:

  • 你好。我的输出仍然相同,在我的代码中它不起作用。我仍然收到:`A B C 0 1 1 1 A B C 0 2 2 2`等等。
  • In my code i have received result like this one 这是你指定的对吗?你是怎么得到这个的?一旦你得到你提到的内容后应用我的代码它将起作用
  • 请在我的问题中查看我的代码。它不是具有多个标题的一帧,它的多个数据帧和每个数据帧都有一个相同的标题,也许这就是它在我的数据集上不起作用的原因?
  • 好吧,男人会看的。你能把你的file.txt中的内容发布一下吗?
  • ,我已经编辑了我的问题,我想我可以在开始时更好地完成我的代码,我从行中获取字母,如果有人可以帮助我只创建一个数据框,如果可以的话有可能我不需要合并我现在拥有的那些数据框。谢谢
【解决方案2】:

我找到了解决方案,我在开始时更改了代码,这很有帮助:

def coordinates():
abc=open('file.txt')
lines=abc.readlines()
        for line in lines:
        abc2=line[20:-7] #i just cut the lines from the begining and from the end, and i dont need to take data from the middle
        abc3=abc2.split()
        pd.DataFrame(abc3) 
        print abc3

coordinates()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多