繁体   English   中英

两个 csv 文件在 python 中读取不同

[英]Two csv files read differently in python

我有两个.csv 文件,数据按日期排列。 我想计算每个月和所有年份的月累计值。 在读取 csv 文件时,它读取没有任何错误。 但是,在计算每月累积值时,对于一个时间序列(在一个 csv 文件中),它是正确的。 但是,对于其他时间序列,相同的代码会出现故障。 我注意到的唯一区别是,当我阅读第一个 csv 文件(带有“日期”和“值”列,总行数 = 826)时,dataframe 有 827 行(最后一行为 nan)。 对于其他 csv 文件,没有观察到这个 nan 事情。

请注意,我的时间序列从 2008 年到 2014 年每年从 06-06-20xx 到 01-10-20xx 开始。 我正在获取每个月的每月累计值,然后删除零值(1 月至 5 月和 11 月至 12 月)。 当我的代码运行时,对于第一个 csv,我从 2008 年 6 月开始获得每月累积值。但是,第二个,它从 2008 年 1 月开始(并且具有非零值,理想情况下应该为零)。

由于我是 python 编码的新手,我无法弄清楚问题出在哪里。 任何帮助表示赞赏。 提前致谢。

这是我的代码:

import pandas as pd
import numpy as np

# read the csv file
df_obs = pd.read_csv("..path/first_csv.csv")
df_fore = pd.read_csv("..path/second_csv.csv")

# convert 'Date' column to datetime index
df_obs['Date'] = pd.to_datetime(df_obs['Date'])
df_fore['Date'] = pd.to_datetime(df_fore['Date'])


# perform GroupBy operation over monthly frequency
monthly_accumulated_obs = df_obs.set_index('Date').groupby(pd.Grouper(freq='M'))['Observed'].sum().reset_index()
monthly_accumulated_fore = df_fore.set_index('Date').groupby(pd.Grouper(freq='M'))['Observed'].sum().reset_index()

有时更冗长但更明确的解决方案效果更好,更灵活,所以这里有一个替代方案,使用convtools

from datetime import date, datetime

from convtools import conversion as c
from convtools.contrib.tables import Table

# generate an ad hoc grouper;
# it's a simple function to be reused further
converter = (
    c.group_by(c.item("Date"))
    .aggregate(
        {
            "Date": c.item("Date"),
            "Observed": c.ReduceFuncs.Sum(c.item("Observed")),
        }
    )
    .gen_converter()
)

# read the stream of prepared rows
rows = (
    Table.from_csv("..path/first_csv.csv", header=True)
    .update(
        Date=c.call_func(
            datetime.strptime, c.col("Date"), "%m-%d-%Y"
        ).call_method("replace", day=1),
        Observed=c.col("Observed").as_type(float),
    )
    .into_iter_rows(dict)
)

# process them
result = converter(rows)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM