首页 > 解决方案 > 使用 for 循环创建和分配不同的变量

问题描述

所以我想做的是以下几点:

我在某个文件夹中有 300 多个 CSV。我想要做的是打开每个 CSV 并只取每个的第一行。

我想做的是以下内容:

import os

list_of_csvs = os.listdir() # puts all the names of the csv files into a list.

以上为我生成了一个列表,例如['file1.csv','file2.csv','file3.csv'].

这很好,但我卡住的地方是下一步。我将使用伪代码对此进行演示:

import pandas as pd

for index,file in enumerate(list_of_csvs):
    df{index} = pd.read_csv(file)    

基本上,我希望我的 for 循环遍历我的list_of_csvs对象,并将第一项读取到 df1,将第二项读取到 df2 等。但是在尝试这样做时,我才意识到 -我不知道如何在执行时更改分配的变量通过迭代分配!!!

这就是提示我问题的原因。我设法找到另一种方法来完成我原来的工作没有问题,但是在交互中进行变量赋值的问题是我无法找到明确答案的问题!

标签: pythonpandas

解决方案


如果我正确理解您的要求,我们可以很简单地做到这一点,让我们使用 Pathlib 而不是os在 python 3.4+ 中添加的

from pathlib import Path
csvs = Path.cwd().glob('*.csv') # creates a generator expression.
#change Path(your_path) with Path.cwd() if script is in dif location

dfs = {} # lets hold the csv's in this dictionary

for file in csvs:
   dfs[file.stem] = pd.read_csv(file,nrows=3) # change nrows [number of rows] to your spec.

#or with a dict comprhension
dfs = {file.stem : pd.read_csv(file) for file in Path('location\of\your\files').glob('*.csv')}

这将返回一个数据帧字典,其中键是 csv 文件名.stem添加它而不添加扩展名。

很像

{
'csv_1' : dataframe,
'csv_2' : dataframe
} 

如果你想连接这些然后做

df = pd.concat(dfs)

索引将是 csv 文件名。


推荐阅读