Pyspark - 多列聚合

问题描述 投票:5回答:1

我有如下数据。文件名:babynames.csv。

year    name    percent     sex
1880    John    0.081541    boy
1880    William 0.080511    boy
1880    James   0.050057    boy

我需要根据年份和性别对输入进行排序,我希望输出汇总如下(此输出将分配给新的RDD)。

year    sex   avg(percentage)   count(rows)
1880    boy   0.070703         3

我不确定如何在pyspark中执行以下步骤。需要你的帮助

testrdd = sc.textFile("babynames.csv");
rows = testrdd.map(lambda y:y.split(',')).filter(lambda x:"year" not in x[0])
aggregatedoutput = ????
python python-2.7 apache-spark pyspark
1个回答
18
投票
  1. 按照the README的说明加入spark-csv package
  2. 加载数据 df = (sqlContext.read .format("com.databricks.spark.csv") .options(inferSchema="true", delimiter=";", header="true") .load("babynames.csv"))
  3. 导入所需的功能 from pyspark.sql.functions import count, avg
  4. 分组和汇总(可选择使用Column.aliasdf.groupBy("year", "sex").agg(avg("percent"), count("*"))

或者:

  • percent转换为数字
  • 重塑为一种格式((yearsex),percent
  • aggregateByKey使用pyspark.statcounter.StatCounter
© www.soinside.com 2019 - 2024. All rights reserved.