【发布时间】:2022-08-06 20:28:51
【问题描述】:
我正在编写一个 python 程序来扫描给定目录的 .csv 文件。我想要每个单词出现的数量作为我的输出。这是我现在编码的。
import os
import pandas as pd
root = D:\\dir1\\dir2\\data
ext = \'.csv\'
dict_napak_file = {} #creating two dictionaries to later try to write data into
dict_napak_dir = {}
for datoteka in os.scandir(root): #going thorugh files in the given directory
if datoteka.path.endswith(ext): #only do below code if the file ends with .csv
df = pd.read_csv(datoteka, encoding = \'cp1252\')
fifth_column = df.iloc[:, 4] # Gets all rows for the fifth column (index starts at 0)
counts = fifth_column.value_counts()
dict_napak_file.update(counts) #this is where the problem starts. It does write in the dictionary. But only for one file
dict_napak_dir = dict_napak_dir.update(dict_napak_file) #Now I want to merge all dictionaries made while scanning the files into one dictionary to use for further data anayisis
print(\"done\")
我收到此错误:
--------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [50], in <cell line: 4>()
8 counts = forth_column.value_counts()
9 dict_napak_dat.update(counts)
---> 10 dict_napak_dir = dict_napak_dir.update(dict_napak_dat)
12 print(\"done\")
AttributeError: \'NoneType\' object has no attribute \'update\'
-
dict_napak_dir.update返回None。而不是dict_napak_dir = dict_napak_dir.update(dict_napak_dat),仅将其更改为dict_napak_dir.update(dict_napak_dat)。当您重新分配时,您将None分配给变量,并且在下一次迭代中它会引发您看到的错误。
标签: python pandas dictionary