大家好,我目前正在处理的数据如下:Example of original data file
总共有51个文件,每个文件有超过800个振荡列,例如(Time,ID,x1,x2,ID,x1,x2,...),这些列都是未标记的。在文件中,每一行都有不同数量的列,如下所示:Shape of one data file
我需要将所有51个文件合并到一个文件中,然后像这样垂直堆叠列:Example of output file
因此,对于每个时间戳,每个学生都有一个特定的行,其中包含他们的位置x,y。
有人能帮我一下吗,谢谢
我使用以下代码合并了具有不同列的CSV文件,但输出文件的大小是原始文件的两倍(例如,100MB对50MB)。我的方法是使用最大列数合并文件,并展开到每一行。然而,这种方法在数据中创建了许多缺失值,从而增加了输出文件的大小。
import os
import glob
import pandas as pd
def concatenate(indir="C:\Test Files",outfile="F:\Research Assitant\PROJECT_Position Data\Test File\Concatenate.csv"):
os.chdir(indir)
fileList=glob.glob("*.csv")
dfList=[]
for filename in fileList:
### Loop over each line
with open(filename, 'r') as f:
### Skip first four lines
for _ in range(4):
next(f)
### Get the numbers of columns in each line
col_count = [ len(l.split(",")) for l in f.readlines() ]
### Read the current csv file
df = pd.read_csv(filename, header=None, delimiter=",", names=range(max(col_count)),
skiprows=4, keep_default_na=False, na_values=[""])
### Append to the list
dfList.append(df)
concatDf=pd.concat(dfList,axis=0)
concatDf.to_csv(outfile,index=None)
有没有办法减小输出文件的大小?或者是在python中处理异构CSV文件的更有效的方法?
合并所有CSV文件后,如何垂直堆叠这些列?
发布于 2020-03-24 02:49:32
with open(os.path.join(working_folder, file_name)) as f:
student_data = []
for line in f:
row = line.strip().split(",")
number_of_results = round(len(row[1:]) / 4) # if we do not count time column, data repeats every 4 times
time_column = row[0]
results = row[1:]
for i in range(number_of_results):
data = [time_column] + results[i*4: (i+1)*4]
student_data.append(data)
df = pd.DataFrame(student_data, columns=["Time", "ID", "Name", "x1", "x2"])
df
https://stackoverflow.com/questions/60823154
复制相似问题