简体   繁体   English

将目录中的csv文件另存为单独的数据框

[英]Save csv files from the directory as a separate dataframes

I have several files csv in the directory 我在目录中有几个csv文件

目录

What I need to do is to iterate ( specifically iterate , because I will do other calculations over the data) in the folder over the files and read them using pandas.read_csv as a separate DataFrames . 我需要做的是迭代( 特别是迭代 ,因为我将对数据进行其他计算)在文件上的文件夹中,并使用pandas.read_csv作为单独的DataFrames进行读取

What I have wrote is the following: 我写的是以下内容:

for i in os.listdir(directory):
    data = pd.read_csv(directory+ '/' +i, encoding="utf8")

When I execute the code above it writes down only the last step's data in the df and when I change the code to the one below: 当我执行上面的代码时,它只会在df中记录最后一步的数据,而当我将代码更改为以下代码时:

for i in os.listdir(directory):
    data[i] = pd.read_csv(directory+ '/' +i, encoding="utf8")

data[i] is marked by red data[i]用红色标记

Could anyone help with this? 有人可以帮忙吗?

If you change your 2nd code snippet to be like this, then it should work, and your dictionary will have keys of the name of the file, and the values will be Dataframes of the corresponding data. 如果将第2个代码段更改为这样,则它将起作用,并且字典中将具有文件名的键,而值将是相应数据的数据帧。

data = {}
for i in os.listdir(directory):
    data[i] = pd.read_csv(directory+ '/' +i, encoding="utf8")

# or using fancy dictionary comprehensions & f-strings (needs recent python3 release)
data = {path: pd.read_csv(f'{directory}/{path}', encoding="utf8")
    for path in os.listdir(directory)}

# or using pathlib
from pathlib import Path
data = {path.name: pd.read_csv(path, encoding="utf8"
    for path in Path(directory).iterdir()}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM