我有一个简单的 CSV 文件,我不知道如何将其放入数据框中。
测试.csv
h1 h2 h3
11 12 13
h4 h5 h6
14 15 16
如您所见,如果上面的 csv 被拆分成两个单独的文件,那么将它们读入数据帧将很容易。每组数据之间有一个空格,它们的长度总是相同的。
我要创建的数据框:
h1 h2 h3 h4 h5 h6
11 12 13 14 15 16
最佳答案
不如 CT Zhu 的解决方案高效和聪明,但可能更简单一些:
import pandas as pd
from StringIO import StringIO
with open ('foo.csv', 'r') as myfile:
data = myfile.read().split('\n\n')
pieces = [pd.read_csv(StringIO(x),sep=' ') for x in data]
print pd.concat(pieces,axis=1)
h1 h2 h3 h4 h5 h6
0 11 12 13 14 15 16
1 10 10 10 10 10 10
关于csv - 读取具有多个 header 的 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23165147/