我有一组 .csv 电子表格,我想将其存储在字典中。我希望电子表格的名称是字典键,字典值是保存为字典的电子表格。在子字典中,我希望列标题作为键,列值作为字典值,保存为 float 。我的代码做了一些事情,但我不太清楚它到底在做什么。
import os
import csv
os.chdir("pathGoesHere")
path=os.getcwd()
rivers=[]
riverDat={}
for sheet in os.listdir(path):
if sheet.endswith(".csv"):
temp={}
name=sheet[0:-4]
rivers.append(name)
reader=csv.QUOTE_NONNUMERIC(open(sheet))
for i in reader:
key=i[0]
temp[key]=i[1]
print(temp)
最佳答案
如果您可以使用 pandas 模块,则此代码应该可以达到目的。请注意,riversDict 是输出字典。
import pandas as pd
riversDict={}
for sheet in os.listdir(path):
if sheet.endswith(".csv"):
name=sheet[0:-4]
dataIn=pd.read_csv(sheet)
dataIn=dict(dataIn.apply(pd.to_numeric, errors='coerce'))
riversDict[name]=dataIn
print(riversDict)
关于python - 尝试在 Python 循环中使用 .csv 文件填充嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59741551/