如何根据熊猫中的条件在特定行开始读取excel文件

时间:2020-07-08 16:54:16

标签: python excel pandas

我读取了通常如下格式的excel文件:

colA colB
   0    0
   1    1

我可以写类似df = pd.read_excel(filename, skiprows=0)

跳过列标题并提取数据。但是有时候我的数据输入为

some random text in the cells above
colA colB
   0    0
   1    1

在这里,我需要手动删除该多余的行,然后将所有内容上移,以便第一行由列标题组成。是否有一种优雅的方法可以在发现任何行号colA的情况下启动excel读取,因此我们跳过了colA和colB标头上方的任何不必要的条目或文本?

2 个答案:

答案 0 :(得分:1)

假设您知道第一列名称(即示例中的webClientBuilder.build() .post() .uri(ccpApiUrl) //.accept(MediaType.APPLICATION_JSON) .bodyValue(customerRequest) .exchange() .doOnSuccess( clientResponse -> logger.info("clientResponse.headers() = " + clientResponse.headers()) ) .doOnSuccess( clientResponse -> { logger.info("clientResponse.statusCode() = " + clientResponse.statusCode()); getStatus(clientResponse.statusCode()); }) //.timeout(Duration.ofSeconds(5)) .flatMap(clientResponse -> clientResponse.bodyToMono(CcpResponse.class)) // .retryWhen(fixedRetry) .block(); ),并且该值将出现在数据的第一列中的某个位置:

colA

答案 1 :(得分:1)

我不太了解您的问题。您似乎了解skip_rows。 您只需传递一个行号列表即可。

skiprows : list-like, int or callable, optional
        Line numbers to skip (0-indexed) or number of lines to skip (int)
        at the start of the file.

例如,

rows_to_skip=[0,1,2] #skip first 3 rows of the file
df = pd.read_excel(filename, skiprows=rows_to_skip)

还有一种方法可以稍微简化该过程。说,您不知道列标题所在的确切行。您可以使用grep在终端中获取此号码,而无需删除之前的所有行。

例如,grep -n 'colA' filename将返回找到该信息的行以及行号。您可以轻松地创建列表来跳过所有之前的行,例如rows_to_skip=list(range(line_number))。不是最好的解决方案(由于list而导致的内存问题),但它也应该在这里起作用。