尝试将原始csv文件的选定行复制到新的csv文件时,请保持提示错误。我只想将第2列包含“ B”的行复制到新的csv文件中,对于“ M”中的行也类似。我面临的另一个挑战是因为原始CSV文件包含浮点数。
设法重命名我的标头并写入新的csv文件,因为原始标头过于冗长,因此请考虑使用数字重新标记它们以便于调用。
import csv
with open("breast_cancer_v1.csv", newline='') as original, open("benign.csv", "w", newline='') as benign:
fieldnames = ['1', '2','3','4','5','6','7','8','9','10','11']
writer = csv.DictWriter(benign, fieldnames)
writer.writeheader()
print ("\nColumn \ Description title", "\n1: ID", "\n2: Diagnosis", "\n3: a) radius (mean of distances from center to points on the perimeter)", "\n4: b) texture (standard deviation of gray-scale values)", "\n5: c) perimeter", "\n6: d) area", "\n7: e) smoothness (local variation in radius lengths)", "\n8: f) compactness (perimeter^2 / area - 1.0)", "\n9: g) concavity (severity of concave portions of the contour)", "\n10: h) concave points (number of concave portions of the contour)", "\n11: i) symmetry", "\n12: j) fractal dimension (coastline approximation - 1)")
csv_file = csv.DictReader(original, fieldnames)
next(csv_file)
col_1 = 3
col_2 = 4
B_row_count = 0
M_row_count = 0
B_sum = 0
M_sum = 0
for row in csv_file:
if (row['2'] == "B"):
B_sum += float(row[str(col_1)])
B_row_count += 1
writer.writerow(row)
elif (row['2'] == "M"):
M_sum += float(row[str(col_1)])
M_row_count += 1
print ("\nNo. of patients (rows) under benign(B) group is: " + str(B_row_count))
print ("No. of patients (rows) under malignant(M) group is: " + str(M_row_count))
print ("\nTotal No. of patients (rows) is: " + str(B_row_count + M_row_count))
错误消息为:
回溯(最近一次通话最近):文件“ C:\ Users \ User \ Desktop \ final coursework \ Final coursework.py”,第69行,在 B_sum + = float(row [str(col_1)])文件“ C:\ Users \ User \ AppData \ Local \ Programs \ Python \ Python35-32 \ Lib \ csv.py”, 第153行,在writerow中 返回self.writer.writerow(self._dict_to_list(rowdict))文件“ C:\ Users \ User \ AppData \ Local \ Programs \ Python \ Python35-32 \ Lib \ csv.py”, _dict_to_list中的第149行 +“,” .join([[repr(x)for right_fields中的x]]))buildins.ValueError:dict包含不在字段名中的字段:None