我想处理一个 csv 文件,我想要的输出是每列不同值的数量(这应该在 unique_list
中)和列中的数据类型(在 'types_list' 中)
到目前为止,我所拥有的是一个嵌套循环:
for unique_list
:返回一个包含所有唯一值的列表,我试图通过创建另一个列表来解决这个问题,该列表在每次迭代中都填充了相应的唯一列项目作为另一个列表,所以我可以在另一个步骤中计算列表中每个列表的项目,但到目前为止我未能实现
for types_list
:在这里我想实现几乎相同的事情,一个列表列表,其中每个“子列表”包含一列的数据类型 - 我尝试了这个,可以在代码,但我得到的结果是一个列表列表,其中子列表确实包含一列的数据类型,但这会重复多次而不是一次。
在这里的下一步中,我想遍历每个列表以检查子列表中的数据类型是否都相同,如果是,则将相应的类型附加到列表中(如果它们不相同,则附加“对象”到此列表)。
我知道使用 Pandas 等可能更容易,但我想为此使用纯 python
with open(filePath,'r') as f:
reader = csv.reader(f)
l=list(reader)
rows = len(l)-1 #counts how many rows there are in the CSV, -1 to exclude the header
columns = len(l[0]) #the number of columns is given by the number of objects in the header list, at least in a clean CSV
without_header = l[1:] #returns the csv list without the header
unique_list = []
types_list = []
looping_list = []
for x in range(0,columns):
looping_list = [item[x] for item in without_header]
worklist = []
for b in looping_list:
try: #here i'm trying if the value in the CSV file could be an integer just in case it isn't recognised as one
int(b)
worklist.append('int')
types_list.append(worklist)
except:
worklist.append(type(b))
types_list.append(worklist)
for n in looping_list:
if n not in unique_list:
unique_list.append(n)
例如,对于此 CSV:
Position,Experience in Years,Salary
Middle Management,5,5000
Lower Management,2,3000
Upper Management,1,7000
Middle Management,5,5000
Middle Management,7,7000
Upper Management,10,12000
Lower Management,2,2000
Middle Management,5,500
Upper Management,7, NoAnswer
我希望 unique_list 返回 [3,5,7] 和 types_list 返回 [str,int,object]
答案 0 :(得分:0)
从文件中读取应该在 'with' 语句中,否则文件已经关闭,读取它会引发异常。
with open(filePath, 'r') as f:
reader = csv.reader(f)
l = list(reader)
对于type_list:您使用字符串'int' 来表示一个int,但使用类型类'str' 来表示一个字符串。我认为您应该始终使用一种或另一种,即使用类型类 int 来表示 int 对象。
在嵌套循环中,您为列项目的每次迭代附加您的工作列表,您不应该只在完成对列的循环后才这样做吗?那是在嵌套循环完成之后。
for x in range(0, columns):
looping_list = [item[x] for item in without_header]
worklist = []
for b in looping_list:
try:
int(b)
worklist.append(int)
except:
worklist.append(type(b))
types_list.append(worklist)
要将每个子列表合并为 1 个值,我们可以将子列表转换为 Set。 Set 删除重复项,因此如果其长度为 1,我们知道子列表仅包含 1 个唯一项。
# uniting the sublist into 1 value
new_types_list = []
for sub_list in types_list:
if len(set(sub_list)) == 1:
# if all items in the sublist are the same
# use the first value in the list
new_types_list.append(sub_list[0])
else:
# they are not all the same
new_types_list.append(object)
对于 unique_list:您尝试使用在循环中创建的变量,在该循环中您对列进行迭代,因此它只包含最后一列中的项目。