[英]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.