【发布时间】:2021-08-10 20:33:43
【问题描述】:
我创建了一个逻辑,即计算有多少人购买了相同的产品。 它有效,但确实效率低下(一直耗尽内存)。
因此,我希望有人有一个比我的内存消耗更少的逻辑。
这就是我所做的:
df: # Please note: below you can find the code to duplicate this.
Order_Number Country Product
1 Ger [A,B]
2 NL [A,B,C]
3 USA [C,D]
4 NL [B,C,D]
5 GER [A]
我想知道有多少客户购买了相同的产品(显然至少有两种产品):
list_df = [df]
# Example for two products bought together
for X in list_df : #
#print(X)
combinations_list = []
for row in X.Product:
combinations = list(itertools.combinations(row, 2)) # Only counting for 2 products here
combinations_list.append(combinations)
Products_DF = pd.Series(combinations_list).explode().reset_index(drop=True)
Products_DF = Products_DF.value_counts()
Products_DF = Products_DF.to_frame()
Products_DF.reset_index(level=0, inplace=True)
Products_DF = Products_DF.rename(index = str, columns = {"index":"Product"})
Products_DF = Products_DF.rename(index = str, columns = {0:"Occurrence"})
Products_DF['Product_Combinations'] = 2 # Only counting for 2 products here
Products_DF['Country'] = X['Country']
main_dataframe = main_dataframe.append(Products_DF, ignore_index = True)
del(Products_DF)
然后,我对一起购买的 3、4、5、6 和 7 产品再次进行上述操作。将所有信息附加到我的 main_dataframe 中。
结果是一个数据框,包含国家、一起购买的产品和事件。就像下面数据的输出一样。
提前非常感谢!
PS我也对 PySpark 解决方案持开放态度(感谢一切!)
完整示例:
import pandas as pd
import itertools
df= {'Order_Number':['1', '2', '3', '4', '5'],
'Country':['Ger', 'NL', 'USA', 'NL', 'Ger'],
'Product': ['[A,B]', '[A,B,C]','[C,D]', '[B,C,D]', '[A]']}
# Creates pandas DataFrame.
df = pd.DataFrame(df)
df = [df] # sorry, this is legacy in my code
main_dataframe = pd.DataFrame()
# Example for two products bought together
for X in df : #
#print(X)
combinations_list = []
for row in X.Product:
combinations = list(itertools.combinations(row, 2)) # Only counting for 2 products here
combinations_list.append(combinations)
Products_DF = pd.Series(combinations_list).explode().reset_index(drop=True)
Products_DF = Products_DF.value_counts()
Products_DF = Products_DF.to_frame()
Products_DF.reset_index(level=0, inplace=True)
Products_DF = Products_DF.rename(index = str, columns = {"index":"Product"})
Products_DF = Products_DF.rename(index = str, columns = {0:"Occurrence"})
Products_DF['Product_Combinations'] = 2 # Only counting for 2 products here
Products_DF['Country'] = X['Country']
main_dataframe = main_dataframe.append(Products_DF, ignore_index = True)
del(Products_DF)
【问题讨论】:
标签: python pandas performance pyspark itertools