pandas 如何从多个CSV文件创建一个字典的数组

5anewei6  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(77)

我正在pandas中加载一个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]))


(Note,这里我只提供两个csv文件作为示例)不幸的是,这不起作用(没有错误消息,但pd dfs不存在)。
任何提示/链接到以前的问题将不胜感激,因为我还没有发现任何类似的Stackoverflow。

e4eetjau

e4eetjau1#

1.使用pathlib设置文件的路径p
1.使用.glob方法查找与模式匹配的文件

  • 使用pandas.read_csv创建一个嵌套框架
  • 使用dict解析来创建一个dict的数组,其中每个文件都有自己的键值对。
  • 像使用其他dict一样使用dict;键是文件名,值是字符串。
  • 或者,使用pandas.concat的列表解析来从所有文件创建一个单独的框架。
  • 在OP中的for-loop中,对象(变量)不能以这种方式创建(例如names[i])。
  • 这相当于'premier10' = pd.read_csv(...),其中'premier10'str类型。
  • 请参阅Import multiple CSV files into pandas and concatenate into one DataFrame以创建一个DataFrame并添加一个列名称和源文件名。
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])

字符串

myzjeezk

myzjeezk2#

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

cetgtptt

cetgtptt3#

这就是你想要的:

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

字符串

相关问题