当前位置: 首页 > 知识库问答 >
问题:

熊猫在自定义日期(月-年)到(月-年N)之间循环绘制

晏阳飙
2023-03-14

我一直在分析几个月的数据,然后每月生成并保存一个数字。到目前为止,当这些都在同一日历年内时,这非常有效,但我很困惑,当数据跨越到下一年时,如何指示循环工作。

示例代码:

import pandas as pd
import datetime as datetime
import matplotlib as plt

df = pd.read_csv("file.csv")
df.index = df.Datetime

for month in range(4,12): #Data starts in April in this example
    fig, axes = plt.subplots(nrows=2,ncols=1, sharex=True, figsize =(18,10))
    startDate = datetime.date(2016,month,1)
    stopDate = datetime.date(2016,month+1,1)
    date_val = startDate.strftime("%B %Y")

    k=0
    df.PRe[startDate:stopDate].plot(ax=axes[k])
    #ylim, xlim, title etc
    k=1
    df.PRp[startDate:stopDate].plot(ax=axes[k])

    plt.savefig("PRe and PRp in %s.png"%date_val,bbox_inches="tight")

这个SO问题很接近,尽管他们使用熊猫日期时间对象而不是我使用的datetime.date对象。我是否应该修改代码以适应解决方案,如果是,如何修改?否则,一旦我们超过2016年,有没有熊猫/蟒蛇的方法让它发挥作用——无论是已知的开始和结束日期,还是更好的是,任何开始和结束日期?

共有2个答案

蒋骏
2023-03-14

@jezrael的回答解决了这个问题;下面是给后代的解决方案

import pandas as pd
import matplotlib as plt

df = pd.read_csv("file.csv")
df.index = df.Datetime

startDate = df.index[0] #seed the while loop, format Timestamp
while (startDate >= df.index[0]) & (startDate < df.index[-1]): 
    fig, axes = plt.subplots(nrows=2,ncols=1, sharex=True, figsize =(18,10))

    stopDate = (startDate + pd.offsets.MonthBegin())#stopDate also Timestamp
    date_val = startDate.strftime("%B %Y")#Date as Month Year string

    k=0
    df.PRe[startDate:stopDate].plot(ax=axes[k])
    #ylim, xlim, title etc
    k=1
    df.PRp[startDate:stopDate].plot(ax=axes[k])
    #ylim, xlim, title etc
    plt.savefig("PRe and PRp in %s.png"%date_val,bbox_inches="tight")
    startDate = stopDate
仰城
2023-03-14

您可以使用日期偏移量

month = 4
startDate = datetime.date(2016,month,1)
print (startDate)
stopDate = (startDate + pd.offsets.MonthBegin()).date()
print (stopDate)
2016-04-01
2016-05-01
month = 4
startDate = datetime.date(2016,month,1)
print (startDate)
stopDate = (startDate + pd.offsets.DateOffset(months=1)).date()
print (stopDate)
2016-04-01
2016-05-01

另一种解决方案是datetimeindex部分字符串索引,如果需要,请按选择:

df.PRe['2016-4'].plot(ax=axes[k])
df.PRe[str(2016)+'-'+str(month)].plot(ax=axes[k])

解决方案,如果需要,按唯一年份循环datetimeindex,按唯一月份循环monthperiod bydatetimeindex.to_period

start = pd.to_datetime('2015-10-24')
rng = pd.date_range(start, periods=10, freq='3W')

df = pd.DataFrame({'PRe': np.random.randint(10, size=10)}, index=rng)  
print (df)
            PRe
2015-10-25    2
2015-11-15    3
2015-12-06    3
2015-12-27    1
2016-01-17    8
2016-02-07    4
2016-02-28    2
2016-03-20    6
2016-04-10    8
2016-05-01    0
2015-10-25    2
for date in df.index.to_period('m').unique():
    print (df.PRe[str(date)])

Freq: 3W-SUN, Name: PRe, dtype: int32
2015-11-15    3
Freq: 3W-SUN, Name: PRe, dtype: int32
2015-12-06    3
2015-12-27    1
Freq: 3W-SUN, Name: PRe, dtype: int32
2016-01-17    8
Freq: 3W-SUN, Name: PRe, dtype: int32
2016-02-07    4
2016-02-28    2
Freq: 3W-SUN, Name: PRe, dtype: int32
2016-03-20    6
Freq: 3W-SUN, Name: PRe, dtype: int32
2016-04-10    8
Freq: 3W-SUN, Name: PRe, dtype: int32
2016-05-01    0
Freq: 3W-SUN, Name: PRe, dtype: int32
 类似资料:
  • 我试图在我正在创建的C#应用程序中显示两个日期之间的年、月和日。(使用控制台进行测试) 我正在使用NodaTime来实现这一点,但在接下来的几个月里,我遇到了一些问题。 我已经阅读了这里的大部分问题和答案,但没有找到任何我可以从中受益的东西。 大多数时候函数工作但有时它不添加月如果天 我使用这个代码进行测试 (2017, 10, 16)和(2018, 1, 15)应该显示为3个月,但它们显示为2个

  • 我有两次约会。一个是以YYYYMMDD格式从其他应用程序的表中检索的,第二个日期是本地时间,我需要这两个日期之间的天数/月/年。 我试过了 但这给了我一些乱七八糟的数字。 变量$t=Fri Dec31 00:00:00 9999 变量$今天=Wed Feb19 14:40:55 2020 产出:25182094888 有什么想法吗?提前谢谢。

  • 问题内容: 我有以下数据框: 我需要按年份和月份对数据进行分组。例如:按2013年1月,2013年2月,2013年3月等分组。我将使用新分组的数据创建一个显示每年/每月abc vs xyz的图表。 我已经尝试了groupby和sum的各种组合,但是似乎什么也无法工作。 感谢您的协助。 问题答案: 您可以使用重采样或(在后台重采样)。 首先,请确保datetime列实际上是datetimes(用命中

  • 我有以下数据框: 我需要按年和月分组数据。即:按2013年1月、2013年2月、2013年3月等分组...我将使用新分组的数据来创建一个显示每年/每月abc vs xyz的图表。 我尝试过groupby和sum的各种组合,但似乎没有任何效果。 谢谢你的帮助。

  • 问题内容: 该的getTime()获取以毫秒为某一特定日期时间。能否可靠地用于18世纪的约会。我们使用Millis并将其存储在字符串变量中以备将来比较。过去可以使用多长时间有限制? 问题答案: 如果您要比较遥远的过去的日期/时间,我强烈建议您看一下JodaTime。或者实际上是任何类型的日期/时间比较和计算。这是一个很棒的图书馆! 不要依靠getTime()做你想做的事情。至少考虑使用Java的C

  • 我已经搜索了4个小时了,但是还没有找到一个用JavaScript计算两个日期(年、月和天)之间差异的解决方案,比如:2010年4月10日是3年、x月和y天之前。 有很多解决方案,但它们只提供了日、月或年的格式差异,或者它们不正确(意味着没有考虑一个月或闰年的实际天数,等等)。做那件事真的有那么难吗? 我看了一下: http://momentjs.com/->只能输出年、月或天的差异 http://