【问题标题】:How can I reshape this multi-dimensional list to a 2D array?如何将这个多维列表重塑为二维数组?
【发布时间】:2019-09-04 09:47:35
【问题描述】:

我知道这个问题已经被问过几十次了,我试图获得使用多维数组的直觉(herehere),但我无法弄清楚这个过程。

我使用来自Calendar 库的yeardatescalendar() 获取一年中的几天、几周、几个月,并打包到一个4D 列表中。

import calendar

cal = calendar.Calendar()
yr_11 = cal.yeardatescalendar(2011)

返回值是月份行列表。每个月行最多包含 3 个月。每个月包含 4 到 6 周,每周包含 1 到 7 天。

我正在尝试将其转换为二维数组,因此它只是一个周列表。但即使我试图这样做,我也不理解输出。

# create an array
arr = np.array(yr_11)

arr.ndim # this returns '2'

arr.shape # this returns (4,3)

# yr_11 holds 63 weeks, so I tried to reshape
new_array = arr.reshape(63,1)

但它会抛出错误:ValueError: cannot reshape array of size 12 into shape (63,1)

有人能解释一下发生了什么并帮助将其转换为二维数组吗?

编辑:基本上我正在寻找这个

[[datetime.date(2010, 12, 27),
 datetime.date(2010, 12, 28),
 datetime.date(2010, 12, 29),
 datetime.date(2010, 12, 30),
 datetime.date(2010, 12, 31),
 datetime.date(2011, 1, 1),
 datetime.date(2011, 1, 2)],
[datetime.date(2011, 1, 3),
 datetime.date(2011, 1, 4),
 datetime.date(2011, 1, 5),
 datetime.date(2011, 1, 6),
 datetime.date(2011, 1, 7),
 datetime.date(2011, 1, 8),
 datetime.date(2011, 1, 9)], ... ]

【问题讨论】:

    标签: python arrays numpy multidimensional-array reshape


    【解决方案1】:

    yeardatescalendar 返回的嵌套list 具有以下层次结构:

    • 多月块

    因此,例如,yr_11[2][1][3][2] 将在第 3 块中给出代表第 2 个月第 4 周第 3 天的 datetime。请记住,索引是从左(嵌套最少)到右(嵌套最多)进行的,但我们通常以相反的方向读取这些元素(最细化的优先)

    为了简化我们的计算,我们可以传递width=12,这样我们的结果将包含一个包含 12 个月的数据块。

    接下来,只需将list 展平并将结果传递给np.array

    import calendar
    
    cal = calendar.Calendar()
    yr_11 = cal.yeardatescalendar(2011, width=12)
    
    flat = [day for month in yr_11[0] for week in month for day in week]
    dates = np.array(flat)
    
    print(dates)
    

    输出:

    [datetime.date(2010, 12, 27) datetime.date(2010, 12, 28)
     datetime.date(2010, 12, 29) datetime.date(2010, 12, 30)
     datetime.date(2010, 12, 31) datetime.date(2011, 1, 1)
     ...
     datetime.date(2011, 12, 28) datetime.date(2011, 12, 29)
     datetime.date(2011, 12, 30) datetime.date(2011, 12, 31)
     datetime.date(2012, 1, 1)]
    

    【讨论】:

    • 我很难真的试图理解这一点,所以谢谢!我会接受你的回答,但我需要一个周列表,而不是日期列表。我进行了编辑,以便您了解我的意思。
    • @Bn.F76 flat = [week for month in yr_11[0] for week in month] 如果您需要几周的时间。
    • @mgds 这非常有帮助!最后一件事,最初当我将列表转换为数组arr并调用arr.ndim时,如果维度为4,为什么它返回2。同样,为什么shape (4,2)size 12
    • @Bn.F76 np.array 的每个维度必须具有相同的长度。但是,显然有些月份的周数比其他月份多,因此 numpy 没有将内部 lists 扩展为数组,而是将它们视为单个对象。
    猜你喜欢
    • 2017-09-12
    • 1970-01-01
    • 2017-05-06
    • 2023-02-19
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    相关资源
    最近更新 更多