我有以下JSON结构:
{
"stuff": 1, "some_str": "srt", list_of_stuff": [
{"element_x":1, "element_y":"22x"},
{"element_x":3, "element_y":"23x"}
]
},
{
"stuff": 2, "some_str": "srt2", "list_of_stuff": [
{"element_x":1, "element_y":"22x"},
{"element_x":4, "element_y":"24x"}
]
},
当我把它作为json:
读入PySpark DataFrame时import pyspark.sql
import json
from pyspark.sql import functions as F
from pyspark.sql.types import *
schema = StructType([
StructField("stuff", IntegerType()),
StructField("some_str", StringType()),
StructField("list_of_stuff", ArrayType(
StructType([
StructField("element_x", IntegerType()),
StructField("element_y", StringType()),
])
))
])
df = spark.read.json("hdfs:///path/file.json/*", schema=schema)
df.show()
我得到以下内容:
+--------+---------+-------------------+
| stuff | some_str| list_of_stuff |
+--------+---------+-------------------+
| 1 | srt | [1,22x], [3,23x] |
| 2 | srt2 | [1,22x], [4,24x] |
+--------+---------+-------------------+
似乎像PySpark一样扁平化了ArrayType的键名,虽然我在df.printSchema()
时仍能看到它们:
root
|-- stuff: integer (nullable = true)
|-- some_str: string (nullable = true)
|-- list_of_stuff: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- element_x: integer (nullable = true)
| | |-- element_y: string (nullable = true)
问题:
我需要计算我的DataFrame中element_y
的不同出现次数。所以给定示例JSON,我会得到这个输出:
22x: 2, 23x: 1, 24x :1
我不确定如何进入ArrayType并计算子元素element_y
的不同值。任何帮助表示赞赏。
答案 0 :(得分:2)
执行此操作的一种方法是使用rdd
,flatten
使用flatMap
数组,然后计算:
df.rdd.flatMap(lambda r: [x.element_y for x in r['list_of_stuff']]).countByValue()
# defaultdict(<class 'int'>, {'24x': 1, '22x': 2, '23x': 1})
或者首先使用数据框explode
列,然后您可以访问每个数组中的element_y
; groupBy
element_y
,然后count
应该提供您需要的结果:
import pyspark.sql.functions as F
(df.select(F.explode(df.list_of_stuff).alias('stuff'))
.groupBy(F.col('stuff').element_y.alias('key'))
.count()
.show())
+---+-----+
|key|count|
+---+-----+
|24x| 1|
|22x| 2|
|23x| 1|
+---+-----+