在 Python 3 中,我尝试从 4 个列表生成这种格式的序列
<yyyymmdd>-<1-200>-<1-20>-<1-13000>
20161201-1-1-1
20161201-1-1-2
20161201-1-1-3
..
..
20161201-1-2-1
20161201-1-2-2
..
..
20161201-2-1-1
20161201-2-1-2
..
20161202-1-1-1
20161202-1-1-2
..
..
20190701-200-20-13000
第一个列表的日期范围为 <yyyymmdd to yyyymmdd>
,其余 3 个列表在 <1-200> <1-20> and <1-13000>
范围内.
所有列表值均采用 str 格式。
现在我正在尝试执行以下操作:
import itertools
import pandas as pd
all_dates = [d.strftime('%Y%m%d') for d in pd.date_range('20160119','20191226')]
all_users = list(range(0,200))
all_products = list(range(0,15))
all_customers = list(range(0,13000))
date_user_product_map = []
date_user_product_customer_map = []
for pair in itertools.product(all_dates,all_users, all_products):
date_user_product_map.append('-'.join(pair))
for pair in itertools.product(date_user_product_map,all_customers):
date_user_product_customer_map.append('-'.join(pair))
第一个串联的 3 个列表速度快且占用内存少。 第二个串联刚刚占用了大量内存并且正在被杀死。
我也尝试在 48 GB RAM 系统上运行它,但似乎没有足够的内存来运行它。
我需要一些帮助来解决这个问题,并理解为什么需要这么多内存。我在这里做错了什么?
更新: (我的要求)
所以,我有几个数据帧,其中很少有列,其值采用 -<1-200>-<1-20>-<1-13000> 格式,占用了很大的空间,因此我想要创建所有可能值的列表,然后枚举并创建一个字典,如下所示:
-<1-200>-<1-20>-<1-13000>
20161201-1-1-1:0 20161201-1-1-2 : 1 20161201-1-1-3 : 2 .. .. 20190701-200-20-12999:n-1 20190701-200-20-13000:n
然后将数据帧的值替换为 1,2...n,n-1。
还有其他方法可以做到这一点吗?
最佳答案
您不需要将这些范围转换为列表。
你应该这样做:
import itertools
import pandas as pd
all_dates = (d.strftime('%Y%m%d') for d in pd.date_range('20160119','20191226'))
all_users = range(0,200)
all_products = range(0,15)
all_customers = range(0,13000)
date_user_product_pairs = ( '-'.join(pair) for pair in itertools.product(all_dates,all_users, all_products))
date_user_product_customer_pairs = ( '-'.join(pair) for pair in itertools.product(date_user_product_map,all_customers))
然后您可以使用这些对生成器来获得您需要的内容。
关于python - 迭代和连接 2 个列表占用大量内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55188943/