gpt4 book ai didi

scala - 如何将数据框拆分为具有相同列值的数据框?

转载 作者:行者123 更新时间:2023-12-03 14:51:20 25 4
gpt4 key购买 nike

使用Scala,如何将dataFrame拆分为具有相同列值的多个dataFrame(数组或集合)。
例如,我想拆分以下DataFrame:

ID  Rate    State
1 24 AL
2 35 MN
3 46 FL
4 34 AL
5 78 MN
6 99 FL


至:

数据集1

ID  Rate    State
1 24 AL
4 34 AL


数据集2

ID  Rate    State
2 35 MN
5 78 MN


数据集3

ID  Rate    State
3 46 FL
6 99 FL

最佳答案

您可以收集唯一的状态值,并只需映射到结果数组即可:

val states = df.select("State").distinct.collect.flatMap(_.toSeq)
val byStateArray = states.map(state => df.where($"State" <=> state))


或映射:

val byStateMap = states
.map(state => (state -> df.where($"State" <=> state)))
.toMap


Python中的相同之处:

from itertools import chain
from pyspark.sql.functions import col

states = chain(*df.select("state").distinct().collect())

# PySpark 2.3 and later
# In 2.2 and before col("state") == state)
# should give the same outcome, ignoring NULLs
# if NULLs are important
# (lit(state).isNull() & col("state").isNull()) | (col("state") == state)
df_by_state = {state:
df.where(col("state").eqNullSafe(state)) for state in states}


这里明显的问题是,它需要对每个级别进行完整的数据扫描,因此这是一项昂贵的操作。如果您正在寻找一种仅分割输出的方法,请参见 How do I split an RDD into two or more RDDs?

特别是,您可以编写按感兴趣的列划分的 Dataset

val path: String = ???
df.write.partitionBy("State").parquet(path)


并在需要时回读:

// Depend on partition prunning
for { state <- states } yield spark.read.parquet(path).where($"State" === state)

// or explicitly read the partition
for { state <- states } yield spark.read.parquet(s"$path/State=$state")


根据数据的大小,输入的拆分级别,存储级别和持久性级别,它可能比多个过滤器更快或更慢。

关于scala - 如何将数据框拆分为具有相同列值的数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31669308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com