使用 for 循环创建和分配不同的变量

Yea*_*uch 3 python pandas

所以我想要做的是以下内容:

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

我想做的是以下内容:

import os

list_of_csvs = os.listdir() # puts all the names of the csv files into a list.
Run Code Online (Sandbox Code Playgroud)

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

这很好,但我遇到的问题是下一步。我将使用伪代码演示这一点:

import pandas as pd

for index,file in enumerate(list_of_csvs):
    df{index} = pd.read_csv(file)    
Run Code Online (Sandbox Code Playgroud)

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

这就是我提出问题的原因。我设法找到了另一种方法来完成我原来的工作没有问题,但是这个通过交互进行变量分配的问题是我无法找到明确答案的问题!

Dat*_*ice 12

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

from pathlib import Path
csvs = [csv for csv in Path.cwd().glob('*.csv')]
#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')}
Run Code Online (Sandbox Code Playgroud)

这将返回一个数据帧字典,键是 csv 文件名,.stem添加这个没有扩展名。

很像

{
'csv_1' : dataframe,
'csv_2' : dataframe
} 
Run Code Online (Sandbox Code Playgroud)

如果你想连接这些然后做

df = pd.concat(dfs)
Run Code Online (Sandbox Code Playgroud)

索引将是 csv 文件名。