python - 使用 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 等。但是在尝试这样做时,我才意识到 -我不知道如何在执行时更改分配的变量通过迭代分配!!!
这就是提示我问题的原因。我设法找到另一种方法来完成我原来的工作没有问题,但是在交互中进行变量赋值的问题是我无法找到明确答案的问题!
解决方案
如果我正确理解您的要求,我们可以很简单地做到这一点,让我们使用 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 文件名。
推荐阅读
- flutter - 为什么我的 getRoute() 函数在使用 futureBuilder 时会被多次调用?
- c# - 使用图像顶部的画布显示与列表框读取的图像属性相关的视觉效果
- javascript - Javascript objects from API to tabledata js objects
- terraform - Terraform 在执行计划时输出“错误:不允许变量”
- r - 使用 R 时,有人有硬币问题的解决方案吗?
- sql - 在 SQL Server 的架构中更新每个表中的列
- http - 以 HTTPS 托管的应用程序 .NetCore 不调用 HTTP Rest
- javascript - 让 div 从底部开始
- r - 如何更快地计算排列的“交叉连接”?
- c# - 在表达式树中使用隐式转换运算符