Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取文件并将其放入数据框(优化流程)_Python_Getfiles - Fatal编程技术网

Python 获取文件并将其放入数据框(优化流程)

Python 获取文件并将其放入数据框(优化流程),python,getfiles,Python,Getfiles,我需要获取一个文件并将信息放入python中的数据帧中,这个过程必须重复20次。在运行以下所有代码之前,有没有一种方法可以更快地完成此任务: df = pandas.DataFrame() file20 = os.path.abspath('Fasting/times/20time.csv') time20 = pandas.read_csv(file20, index_col=0, header=0) df['time20'] = time20['Gen1'] + '_'+ time20['

我需要获取一个文件并将信息放入python中的数据帧中,这个过程必须重复20次。在运行以下所有代码之前,有没有一种方法可以更快地完成此任务:

df = pandas.DataFrame() 
file20 = os.path.abspath('Fasting/times/20time.csv')
time20 = pandas.read_csv(file20, index_col=0, header=0)
df['time20'] = time20['Gen1'] + '_'+ time20['Gen2']
file19 = os.path.abspath('Fasting/times/19time.csv')
time19 = pandas.read_csv(file19, index_col=0, header=0)
df['time19'] = time19['Gen1'] + '_'+ time19['Gen2']
file18 = os.path.abspath('Fasting/times/18time.csv')
time18 = pandas.read_csv(file18, index_col=0, header=0)
df['time18'] = time18['Gen1'] + '_'+ time18['Gen2']
file17 = os.path.abspath('Fasting/times/17time.csv')
time17 = pandas.read_csv(file17, index_col=0, header=0)
....
***嗨!我意识到我每次都需要单独保存,因为我以后需要与他们一起工作
time17=pandas.read\u csv(file17,index\u col=0,header=0)
。是否可以在循环中同时执行该操作和数据帧?多谢各位

试试看:

files = [str(i) + 'time' for i in reversed(range(1, 21))]
pieces = []
    # much faster to start with empty list than empty DataFrame

for file in files:
    path = 'Fasting/times/%s.csv' % file
    frame = pd.read_csv(path, index_col=0, header=0)
    pieces.append(frame['Gen1'] + '_' + frame['Gen2'])

df = pd.concat(pieces, axis=1) # may need ignore_index=True
df.columns = files

嗨,非常感谢,这几乎是我所需要的。但是在新的数据帧中,我只需要与文件
df['timei']=timei['Gen1']+'''.'+timei['Gen2']
一样多的列。这样看来,它会将filei中的所有列加上新列(timei['Gen1']+'''.'+'timei['Gen2'])。非常感谢。我明白你的意思——更新我的回答,试试看。它只会为每个文件追加1列。请记住,这是假定文件的列是字符串。为了安全起见,您可以使用
df['Gen1'].astype(str)+''.'+df['Gen2'].astype(str)