我有几个输出文件,这里有两个:
File1中:
4
12
13
6
.....
文件2
20
3
9
14
.....
目标输出:
r_1 r_2
0 4 20
1 12 3
2 13 9
3 6 14
我需要将它们批量加载到庞大的数据框中。这是我的开始:
(1)创建所有文件的数组:
allfiles = []
for root, dirs, files in os.walk(r'/my_directory_path/'):
for file in files:
if file.endswith('.csv'):
allfiles.append(file)
(2)将文件加载到pandas中:(问题在这里)
big = pd.DataFrame
for i in allfiles:
file='/my_directory_path/' + i
big[i] = pd.read_csv(file,sep='\t',header=None)
问题是big[i]
,我需要在传递i
时在for循环中创建一个新列。
答案 0 :(得分:2)
import pandas as pd
import glob
i = 1
dfs = []
#create empty df for output
d = pd.DataFrame()
#glob can use path with *.txt - see http://stackoverflow.com/a/3215392/2901002
#for i in allfiles:
for files in glob.glob('my_directory_path/*.csv'):
#print files
#added name as column name
dfs.append(pd.read_csv(files, sep='\t',header=None, names = ['r_' + str(i)]))
i += 1
p = pd.concat(dfs, axis=1)
print p
print p
r_1 r_2
0 4 20
1 12 3
2 13 9
3 6 14