Skip to main content
 首页 » 编程设计

python之如何按天聚合多列 [Pyspark]

2024年12月31日27think

我想将下面的 pandas 代码转换为 pysaprk。

d = {'has_discount':'count', 
    'clearance':'count', 
    'count': ['count', 'sum'], 
    'price_guide':'max'} 
 
df.index = timestamp2datetime(df.time_create, unit='ms') 
df1 = df.resample('D').agg(d) 
 
df1.columns = df1.columns.map('_'.join) 
d1 = {'has_discount_count':'discount_order_count', 
    'clearance_count':'clearance_order_count', 
    'count_count':'order_count', 
    'count_sum':'sale_count', 
    'price_guide_max':'price_guide'} 
 
df2 = df1.rename(columns=d1) 

但是pysaprk中没有resmaple,尝试改用groupby:

d = {'has_discount':'count', 
    'clearance':'count', 
    'count': ['count', 'sum'], 
    'price_guide':'max'} 
 
df.select(date_format(from_unixtime(df.time_create/1000),'yyyy-MM-dd').alias('day')).groupby('day').agg(d).show(5) 

但是出错了

AnalysisException: u'Cannot resolve column name "price_guide" among (day);' 

Pyspark 的聚合似乎不支持像 d 这样的输入。我该怎么办?

请您参考如下方法:

df.select 您使用的是 day 一列,但在聚合语句中您使用的是其他列。 您可能想要的是将 day 列添加到其他存在的列中:

df.withColumn('day', date_format(from...