Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

python - 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. I need to extract all respective rows from each file and save it as a new file. i.e. first output file must contain first rows of all input files and so on.

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:UsersikraDesktopPandas'
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:UsersikraDesktopPandas'+'\'+files)
            spi1 = dataset.loc[j,'SPI'] 
            data.loc[i]['ObjectID'] = files[:]
            data.loc[i]['SPI'] = spi1
            data.to_csv(r'C:UsersikraDesktopPandasoutput\'+str(j)+'.csv') 
            i + 1

It works well when index (i.e. 'j' ) is specified. But when I tried to loop, the output csv file contains only first row. Where am I wrong?

question from:https://stackoverflow.com/questions/65921394/extracting-all-specific-rows-separately-from-multiple-csv-files-and-combine-ro

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You better use append:

data = data.append(spi1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...