[英]How to create a single dataframe from multiple csv files in a specified directory
csv个文件自己放在一个命名的文件夹中。 将 csv 个文件中的所有数据读取到单个数据框中很有用。 到目前为止,这是一些代码:
#create a variable and look through contents of the directory
files=[f for f in os.listdir("./your_directory") if f.endswith('.csv')]
#Initalize an empty data frame
all_data = pd.DataFrame()
#iterate through files and their contents, then concatenate their data into the data frame initialized above
for file in files:
df = pd.read_csv('./your_directory' + file)
all_data = pd.concat([all_data, df])
#Call the new data frame and verify that contents were transferred
all_data.head()
这给出了错误:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 4-5: truncated \UXXXXXXXX escape
如果有人让这个工作,你能展示一个工作示例吗?
csv 文件自己放置在一个命名文件夹中。 将 csv 文件中的所有数据读取到单个数据框中会很有用。 到目前为止,这里有一些代码:
#create a variable and look through contents of the directory
files=[f for f in os.listdir("./your_directory") if f.endswith('.csv')]
#Initalize an empty data frame
all_data = pd.DataFrame()
#iterate through files and their contents, then concatenate their data into the data frame initialized above
for file in files:
df = pd.read_csv('./your_directory' + file)
all_data = pd.concat([all_data, df])
#Call the new data frame and verify that contents were transferred
all_data.head()
这给出了错误:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 4-5: truncated \UXXXXXXXX escape
如果有人让这个工作,你能展示一个有效的例子吗?
这就是您使用所有代码的方式:
#create a variable and look through contents of the directory
files=[f for f in os.listdir("./your_directory") if f.endswith('.csv')]
#Initalize an empty data frame
all_data = pd.DataFrame()
#iterate through files and their contents, then concatenate their data into the data frame initialized above
for file in files:
df = pd.concat(map(pd.read_csv, glob.glob('./your_directory/*.csv)))
all_data = pd.concat([all_data, df])
#Call the new data frame and verify that contents were transferred
all_data.head()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.