简体   繁体   English

从多个 csv 文件中提取所有特定行(单独)并组合行以另存为新文件

[英]Extracting all specific rows (separately) from multiple csv files and combine rows to save as a new file

I have a number of csv files.我有许多 csv 文件。 I need to extract all respective rows from each file and save it as a new file.我需要从每个文件中提取所有相应的行并将其保存为新文件。 ie first output file must contain first rows of all input files and so on.即第一个 output 文件必须包含所有输入文件的第一行,依此类推。

I have done the following.我做了以下事情。

import pandas as pd
import os
import numpy as np
data = pd.DataFrame('', columns =['ObjectID', 'SPI'], index = np.arange(1,100))
path = r'C:\Users\bikra\Desktop\Pandas'
i = 1
for files in os.listdir(path):
    if files[-4:] == '.csv': 
        for j in range(0,10, 1):
        #print(files) 
            dataset = pd.read_csv(r'C:\Users\bikra\Desktop\Pandas'+'\\'+files)
            spi1 = dataset.loc[j,'SPI'] 
            data.loc[i]['ObjectID'] = files[:]
            data.loc[i]['SPI'] = spi1
            data.to_csv(r'C:\Users\bikra\Desktop\Pandas\output\\'+str(j)+'.csv') 
            i + 1

It works well when index (ie 'j' ) is specified.指定索引(即 'j' )时效果很好。 But when I tried to loop, the output csv file contains only first row.但是当我尝试循环时,output csv 文件只包含第一行。 Where am I wrong?我哪里错了?

You better use append:你最好使用 append:

data = data.append(spi1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从csv文件中提取特定行 - Extracting specific rows from csv files 将多个文件中的特定行分组,并将每组行保存在一个新的 excel 文件中,其中包含 python(pandas,openpyxl) - Group specific rows from multiple files and save each groups of rows in a new excel file with python (pandas, openpyxl) 根据特定关键字从 CSV 文件中提取行 - extracting rows from CSV file based on specific keywords 从csv文件中的多行中提取唯一值 - Extracting unique values from multiple rows in csv file Python:从csv中提取特定行作为列表 - Python: Extracting specific rows from csv as list 读取多个.csv 文件并提取(在新的.csv 文件中)与特定列中的非空单元格对应的所有行 - Read multiple .csv files and extract (in new .csv files) all rows corresponding to non-empty cells across a specific column 如何使用 python 从多个 excel 文件中读取和组合特定行到单个文件中? - How to read & combine specific rows from multiple excel files into a single file using python? 如何将多个csv文件中的行复制到pandas中的新文件? - How to copy rows from multiple csv files to new files in pandas? 从csv文件中的行中提取信息 - extracting information from rows in csv file 迭代地将特定行从CSV文件复制到新文件 - Iteratively copy specific rows from CSV file to new file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM