数据分析学习笔记1—Python 简单处理csv
①读入csv文件并获取所有行所有列内容(存入 row 二重列表中)
row=[]#定义行数组,每行record为一个子list
#注意 encoding 此处为gbk,常用的还有 utf-8
with open("First_work\附件.csv",'r',encoding="gbk") as file1:
reads= file1.readlines()
for line in reads:
row.append(line.strip().split(','))
②删除csv中含空单元格的数据行(数据预处理)
# 数据预处理
# row 列表 去空(根据del_row中数字删除row的行) 为 new_row
new_row=[]
del_row=[] #存放要row中要删除的list的下标
i=0 #观察有多少空行数据
new_row=row
for a_row in row:
for a_record in a_row:
if a_record.strip()=='': #找到含空数据(空串,空格串)的单元格
row_index=row.index(a_row) #获取单元格所在行的下标
del_row.append(row_index) #将要删除的行存入列表
i=i+1
# print(len(row)) 42817
# print(i)
# 逆序遍历del_row并删除list ---不逆序会出错,因为删一个会移动一次,下标改变。。。
for index_num in reversed(del_row):
del new_row[index_num]
#学习: https://www.cnblogs.com/sui776265233/p/9752417.html 简单了解深拷贝浅拷贝。。。
③遍历字典
python字典遍历的几种方法
④将字典内容写出到csv文件,并对浮点数保留两位小数
with open("task1_2.csv",'w',encoding="utf-8",newline='') as file12:
writer=csv.writer(file12)
for k in fare.keys():
writer.writerow([k,"{:.2f}".format(fare[k])])
⑤debug
if month in month_list: #若月份存在,消费金额增加,存入day
month_index=month_list.index(month)
cus_dict[line[0]][month_index][1][0]=float(cus_dict[line[0]][month_index][1][0])+float(money)
cus_dict[line[0]][month_index][1][1]=cus_dict[line[0]][month_index][1][1].append(day)
else: #若月份不存在,新加数据
遇到bug并debug(改正):
cus_dict[line[0]][month_index][1][1]=cus_dict[line[0]][month_index][1][1].append(day) #错误
cus_dict[line[0]][month_index][1][1].append(day) #正确
----2020.11.4