问题描述
我有一个目录,其中包含每个客户的文件夹。在每个客户文件夹中,都有一个名为surveys.csv
的csv文件。我想打开每个客户文件夹,然后从csv中提取数据并进行连接。我还想创建一个具有该客户ID的列,该客户ID是文件夹的名称。
import os
rootdir = '../data/customer_data/'
for subdir,dirs,files in os.walk(rootdir):
for file in files:
csvfiles = glob.glob(os.path.join(mycsvdir,'surveys.csv'))
# loop through the files and read them in with pandas
dataframes = [] # a list to hold all the individual pandas DataFrames
for csvfile in csvfiles:
df = pd.read_csv(csvfile)
df['patient_id'] = os.path.dirname
dataframes.append(df)
# concatenate them all together
result = pd.concat(dataframes,ignore_index=True)
result.head()
此代码仅给我一个包含一个客户数据的数据框。在目录“ ../data/customer_data/”中,应该有大约25个包含客户数据的文件夹。我想将所有surveys.csv
文件中的25个连接成一个数据框。请帮忙
解决方法
放入此行:
dataframes = []
外部for循环。
它会在每个循环中擦除列表。
另一个问题:
- 在此行
csvfiles = glob.glob(os.path.join(mycsvdir,'surveys.csv'))
-使用subdir
获取文件的完整路径。 -
csvfiles
只是一个文件-为什么使用循环读取它?