python - 如何从一年中的一周计算出一个月中的一周?

标签 python pandas date calendar time-series

我找到了一个 node.js解决方案,但找不到 python 解决方案。我有一个看起来像这样的 DataFrame:

   Year  Month      Week  numOfTrips
0  2011  July       30    2608
1  2011  August     31    6852
2  2011  August     32    8092
3  2011  August     33    7674
4  2011  August     34    7065
5  2011  August     35    3896
6  2011  September  35    4182
7  2011  September  36    7315
8  2011  September  37    8929
9  2011  September  38    7822
10 2011  September  39    6508
11 2011  October    39    1848
12 2011  October    40    9233
13 2011  October    41    7818
14 2011  October    42    7627
 .   .      .        .      .
 .   .      .        .      .
 .   .      .        .      .

我想用当月的周数替换每个周数,我该怎么做?

结果如下:

   Year  Month      Week  numOfTrips
0  2011  July       5     2608
1  2011  August     1     6852
2  2011  August     2     8092
3  2011  August     3     7674
4  2011  August     4     7065
5  2011  August     5     3896
6  2011  September  1     4182
7  2011  September  2    7315
8  2011  September  3    8929
9  2011  September  4    7822
10 2011  September  5    6508
11 2011  October    1    1848
12 2011  October    2    9233
13 2011  October    3    7818
14 2011  October    4    7627
 .   .      .        .      .
 .   .      .        .      .
 .   .      .        .      .

最佳答案

我找到了一个似乎可行的相对冗长且丑陋的解决方案。如果有错误/错误或更清晰的实现,请告诉我。

我的方法:使用示例 2011 July 30 2608

  1. 获取相应年份中相应月份的周数
m = list(calendar.month_name).index('July') # turn month name into int
cal = calendar.Calendar()
weeks = cal.monthdatescalendar(2011,7) # get weeks for that month in the year
  1. 获取与您打交道的那一年的每周。在我们的示例中,它是 2011

yr = cal.yeardatescalendar(2011, width=12)

此代码将获取年份并将其存储在一个 4D 列表中:month-junk(在我们的例子中是 12 个月的 1 个垃圾)、month、week、day。要查询,请对 7 月第 5 周的所有日期执行类似 yr[0][6][4][:] 的操作。因此,下一步是将其转换为一个包含所有周的二维数组。

flat = [week for month in yr[0] for week in month]
dates = np.array(flat)

由于 cal.yeardatescalendar() 返回列表的方式,此 dates 将包含重复项。我们删除了这些:

new_dates = []
for date in range(len(dates)):
    if not(np.array_equal(dates[date], np.array(dates[date-1]))):
        new_dates.append(dates[date])

此时,您有一个与周数对齐的二维周数组。如果你去 here ,并检查 201130 周,您会看到它是 7 月的第 5 周。

  1. 接下来,我们使用“正确的”周列表数组来查询我们的周。前任。周 30

the_week = new_dates[:][30]

  1. 最后,我们可以看到当月的一周是哪一周。当我们找到匹配项时,我们知道这是那个星期的编号。
for week in range(len(weeks)): 
    if np.array_equal(the_week, np.array(weeks[week])):
        save_week_num = week+1
        print(save_week_num) # for our example it will print 5

这是一个函数:

def week_of_month(year, month, y_week):
    m = list(calendar.month_name).index(month) 
    cal = calendar.Calendar()
    weeks = cal.monthdatescalendar(year,m) 

    yr = cal.yeardatescalendar(year, width=12)
    flat = [week for month in yr[0] for week in month]
    dates = np.array(flat)

    new_dates = []
    for date in range(len(dates)):
        if not(np.array_equal(dates[date], np.array(dates[date-1]))):
            new_dates.append(dates[date])

    the_week = new_dates[:][y_week] # for 2013, replace this with: the_week = new_dates[:][y_week-1] 

    number = 0
    for week in range(len(weeks)):

        if np.array_equal(the_week, np.array(weeks[week])):

            save_week_num = week+1
            number = save_week_num

    return number

要在问题运行中的 DataFrame 上测试它:

df['Week'] = df.apply(lambda row: week_of_month(row.Year, row.Month, row.Week), axis=1)

关于python - 如何从一年中的一周计算出一个月中的一周?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55667791/

相关文章:

python - 与 MatchObject.group() 相关的 re.sub() 错误

python - 无需使用 BULK INSERT 或 pandas to_sql 即可加快从 CSV 文件插入 SQL Server 的速度

pandas - 类型错误 : <class 'datetime.time' > is not convertible to datetime

python - 什么时候需要在Python中定义单独的函数

python - 如何返回数组中的嵌套文档

Python:根据多个分组对唯一变量进行分组和计数而无需重新计数

python - 没有传递参数的 Lambda 函数

javascript - 简单的 javascript 日期数学......不是真的

javascript - 将时间字符串 ("hours:minute") 转换为日期对象

python - Python 中是否有允许在单个文件中管理虚拟文件系统的库?