如何从多个csv文件创建数据帧?

2024-04-26 03:07:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在熊猫中加载一个csv文件作为

premier10 = pd.read_csv('./premier_league/pl_09_10.csv')

但是,我有20多个csv文件,我希望使用循环和预定义名称将其加载为单独的dfs(每个csv一个df),类似于:

import pandas as pd
file_names = ['pl_09_10.csv','pl_10_11.csv']
names = ['premier10','premier11']
for i in range (0,len(file_names)):
     names[i] = pd.read_csv('./premier_league/{}'.format(file_names[i]))

(注意,这里我仅提供两个csv文件作为示例)不幸的是,这不起作用(没有错误消息,但pd dfs不存在)

如果您有任何关于之前问题的提示/链接,我将不胜感激,因为我在Stackoverflow上没有发现任何类似的内容


Tags: 文件csvimport名称pandasdfreadnames
3条回答

names = ['premier10','premier11']不创建字典,而是创建列表。只需将其替换为names = dict()或将names = ['premier10','premier11']替换为names.append(['premier10','premier11'])

  1. 使用^{}设置文件的路径p
  2. 使用^{}方法查找与模式匹配的文件
  3. 使用^{}创建数据帧
    • 使用dict理解创建数据帧的dict,其中每个文件都有自己的键值对。
      • 像其他口述一样使用口述;键是文件名,值是数据帧
    • 或者,使用带有^{}的列表理解从所有文件创建单个数据帧
  • 在OP中的for-loop中,对象(变量)不能以这种方式创建(例如names[i])。
    • 这相当于'premier10' = pd.read_csv(...),其中'premier10'str类型
from pathlib import Path
import pandas as pd

# set the path to the files
p = Path('some_path/premier_league')  

# create a list of the files matching the pattern
files = list(p.glob(f'pl_*.csv'))

# creates a dict of dataframes, where each file has a separate dataframe
df_dict = {f.stem: pd.read_csv(f) for f in files}  

# alternative, creates 1 dataframe from all files
df = pd.concat([pd.read_csv(f) for f in files])  

这就是你想要的:

#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()

相关问题 更多 >