Objective: To read the contents of CSV file, take out 0 and 1 data strings, count the number of consecutive times and frequency of occurrence of 1
Read the contents of the CSV file first:
Import CSV def csv_read (file): = [] = csv.reader (file) for in csv_reader: # Skip Header if" ": Continue #print (ID, data) list.append (data) return list
And then write the methods for 0 and 1.
#count the number of consecutive 0 and 1 occurrences#function function: To count the number of consecutive occurrences of 1, return a list of successive timesdefsum_times (list): Total_list= [] #n count occurrences, m indicates the current number of processesn =0 M=0 forWinchlist:m+ = 1ifint (W) = = 1: N+ = 1elifint (w) = =0:ifn >0:#print position with more than 2 consecutive times ifn > 2: Print("Continuous Duration:"N"| line number:", M-N) total_list.append (n) n=0#automatically counts if the last one is 1 ifm = =len (list):ifn >0:total_list.append (n) n=0Print("\nsum_times function Print List of consecutive times: \ n", Total_list)returntotal_list#function function: To count the list of occurrence frequencydefsum_tocal (list): List_total=[0, 0, 0, 0, 0] forNinchlist:ifn = = 1: list_total[0]+ = 1elifn = = 2: list_total[1] + = 1elifn = = 3orn = = 4: list_total[2] + = 1elifn = = 5orn = = 6: list_total[3] + = 1elif6 < n <= 12: list_total[4] + = 1returnList_total
Finally, the execution is called sequentially
ImportReadcsv, Tong_ji_ge_shu#number of times the frequency of each time is statistically occurringfile= Open ("D://vis_911_3000.csv")#file = open ("D://ts_ctime_12.csv")#reading data from CSVCsvlist =readcsv.csv_read (file) file.close ()#record the number of hours that appear consecutivelyLIST_PINLV =tong_ji_ge_shu.sum_times (csvlist)#count the number of occurrences of each time periodList_final =tong_ji_ge_shu.sum_tocal (LIST_PINLV)Print()#Blank LinePrint(list_final)#Enter a statistical list of the number of time periods#print ("1 times:" + str (list_final[0]), "| 2 times: "+ str (list_final[1])," | 3-4 times: "+ str (list_final[2]))Print("[1 times, 2 times, 3-4 times, 5-6 times, 7-12 Times]")
Python small app: read a CSV file and process 01 data strings