gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:12:00 25 4
gpt4 key购买 nike

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

我在某个文件夹中有 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 等。但是在尝试执行此操作时我才意识到 - 我不知道如何在通过迭代进行分配时更改正在分配的变量!!!

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

最佳答案

如果我正确理解您的要求,我们可以很简单地做到这一点,让我们使用 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 文件名。

关于python - 使用 for 循环创建和分配不同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59823218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com