计算csv文件中的日期实例数?

2024-10-04 11:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个CSV文件,每个单元格中填充了日期,我想计算每个日期有多少个,然后我将使用matplotlib绘制到条形图上

我不知道如何计算每个日期有多少个实例

我有以下代码来读取csv文件,但不确定从这里去哪里

def Readtoarray():
    with open('Book1.csv','r') as file:
        reader = csv.reader(file, delimiter=',')
        next(reader, None)  # skip the headers
        for row in reader:
            XXXXXXXXX

示例数据:

23/03/2020,6630997
23/03/2020,6630990
20/03/2020,6630390
20/03/2020,6630386

Tags: 文件csv实例代码matplotlibdefwith绘制
3条回答

我想最简单的方法是将csv文件作为数据帧读取,然后使用value_counts()函数

Count the frequency that a value occurs in a dataframe column

import pandas as pd
 
def Readtoarray():
   
   df = pd.read_csv('Book1.csv')
   x = df["Dates"].value_counts() # assuming the column is called Dates

我建议使用计数器dict对象(请参见https://docs.python.org/3/library/collections.html#collections.Counter

def Readtoarray():
    c = collections.Counter()
    with open('Book1.csv','r') as file:
        reader = csv.reader(file, delimiter=',')
        next(reader, None)  # skip the headers
        for row in reader:
            c[row[0]] += 1 # or whatever the row index is for the date(s)
    return c

这将导致以下输出:

>>> for k,v in c.items():
        print(k, ": ", v)

2-Sep :  4
3-Sep :  2
23-Sep :  2

你能提供一个你的CSV日期的例子吗? 要计算Python中某些内容的出现次数,最好的方法是使用^{}

import collections

strings = ["a", "b", "a", "c", "b", "a", "a", "b"]
count = collections.Counter(strings)

count.items() == {"a": 4, "b": 3, "c": 1}

编辑

将日期作为行中的第一个值,假设您不需要对这些日期进行特殊处理,这意味着要解析它们:

import collections

count = collections.Counter([row[0] for row in reader])

它将返回一个dict,其中日期(作为字符串,例如"23/03/2020")作为键,其出现次数作为值。如果希望日期作为datetime.date对象,可以在理解列表中解析它们:

import collections
import datetime

dates = [datetime.datetime.strptime(row[0], "%d/%m/%Y") for row in reader]
count = collections.Counter(dates)

相关问题 更多 >