Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 使用f.read()对字符串进行切片的直接方法,最终将csv作为数据帧读取_Python 3.x_Pandas_Stringio - Fatal编程技术网

Python 3.x 使用f.read()对字符串进行切片的直接方法,最终将csv作为数据帧读取

Python 3.x 使用f.read()对字符串进行切片的直接方法,最终将csv作为数据帧读取,python-3.x,pandas,stringio,Python 3.x,Pandas,Stringio,我有一个.csv文件,我想打开它并最终将其保存为一个数据帧。此文件在数据帧上方有一些垃圾文本,其标题从字符串Sample\u ID开始。我编写了一个代码,它分多个步骤完成这项工作,现在我想知道是否有更优雅的方法来完成这项工作。这是我的密码 import pandas as pd import re from io import StringIO with open('SampleSheet.csv') as f: ## read in the .csv file as a string

我有一个.csv文件,我想打开它并最终将其保存为一个数据帧。此文件在数据帧上方有一些垃圾文本,其标题从字符串
Sample\u ID
开始。我编写了一个代码,它分多个步骤完成这项工作,现在我想知道是否有更优雅的方法来完成这项工作。这是我的密码

import pandas as pd
import re
from io import StringIO

with open('SampleSheet.csv') as f:
    ## read in the .csv file as a string
    step1 = f.read()

    ## subset the step1 file
    # define where my df should start
    start = 'Sample_ID'
    step2 = step1[step1.index(start):]

    ## read in step2 as a pandas dataframe with stringio
    step3 = pd.read_csv(StringIO(step2))
我想知道是否有一种方法可以直接使用
f.read()
,这样我就可以少走一步了


我还尝试将
pd.read\u csv()
skiprows
一起使用,但我在分配以
Sample\u ID开始的行号时遇到了困难

您可以仅使用
read\u csv()
导入和读取文件,如下所示:

df  =   pd.read_csv('SampleSheet.csv', header=3)

where header是数据集开始之前要在文件顶部跳过的行数。

问题是,垃圾行的数量因我拥有的不同文件而异,这就是为什么我必须查找模式
Sample\u ID
它们中没有一个可以做这项工作,因为垃圾行的数量不同(这会影响我要读取的所有
SampleSheet.csv
中的
标题和
skiprows