熊猫read_csv,重复使用跳过的行

时间:2019-08-27 11:55:06

标签: python pandas csv

数据集由10列组成,但前6行是“简介数据”,只有一列

例如,文件如下所示:

dataset_name = data1
date= 1/1/1970
items=1000
... (for 6 lines)

# following by the data itself
column1,column2.column3.....

从网址加载制表符分隔的值数据集, 跳过前6行(不是数据的一部分,而是所需的信息)

data = pd.read_csv(url,skiprows=6, engine='python')

问题: 由于需要顶行, 跳过后如何将已跳过的行取回? (无需两次加载文件...。)

1 个答案:

答案 0 :(得分:0)

您可以从StringIO创建类似文件的对象,并从中读取:

import pandas as pd
import requests
import io

url = 'https://srv-file6.gofile.io/download/su2C6D/so57674146.csv'

resp = requests.get(url)
f = io.StringIO(resp.content.decode())

header = {}
for i in range(6):
    key,val = f.readline().strip().split('=')
    header[key] = val

df = pd.read_csv(f, engine='python')

print(header)
print(df)

csv文件:

dataset_name = data1
date= 1/1/1970
items=1000
line_4=4
line_5=5
line_6=6
column1,column2,column3
1,2,3
10,20,30

示例程序的输出:

{'dataset_name ': ' data1', 'date': ' 1/1/1970', 'items': '1000', 'line_4': '4', 'line_5': '5', 'line_6': '6'}
   column1  column2  column3
0        1        2        3
1       10       20       30