在scala中过滤数据帧
问题描述:
假设我有一个使用案例类模式从文本文件创建的数据帧。以下是存储在数据框中的数据。在scala中过滤数据帧
ID - 型 - QT - P
1,X,10,100.0
2,Y,20%,200.0
1,Y,15%,150.0
1, X,5,120.0
我需要通过“id”和Type筛选数据框。并且对于每个“id”迭代通过数据帧进行一些计算。 我试过这种方式,但没有奏效。代码快照。
case class MyClass(id: Int, type: String, qt: Long, PRICE: Double)
val df = sc.textFile("xyz.txt")
.map(_.split(","))
.map(p => MyClass(p(0).trim.toInt, p(1), p(2).trim.toLong, p(3).trim.toDouble)
.toDF().cache()
val productList: List[Int] = df.map{row => row.getInt(0)}.distinct.collect.toList
val xList: List[RDD[MyClass]] = productList.map {
productId => df.filter({ item: MyClass => (item.id== productId) && (item.type == "X" })}.toList
val yList: List[RDD[MyClass]] = productList.map {
productId => df.filter({ item: MyClass => (item.id== productId) && (item.type == "Y" })}.toList
答
从您的示例中取出独特的想法,只需遍历所有ID并根据当前ID筛选DataFrame。在此之后,你有一个数据帧,只有相关数据:
val df3 = sc.textFile("src/main/resources/importantStuff.txt") //Your data here
.map(_.split(","))
.map(p => MyClass(p(0).trim.toInt, p(1), p(2).trim.toLong, p(3).trim.toDouble)).toDF().cache()
val productList: List[Int] = df3.map{row => row.getInt(0)}.distinct.collect.toList
println(productList)
productList.foreach(id => {
val sqlDF = df3.filter(df3("id") === id)
sqlDF.show()
})
sqlDF在环路与相关数据的DF,以后就可以在其上运行你的计算。
谢谢。有效。 我需要一个更多的帮助,如下所述: sqlDF.foreach(row => {caluculation(row); row.getLong(2)= row.getLong(2) - x}) 所以这里用于每行计算后,我只需要上传row.getLong(2)[单值而不是整列],并保持其余的数据框。 你能建议如何做到这一点? – Advika
@Advika我建议你打开一个新的线程问这个问题。首先它将允许更好地阅读它,并将它暴露给更多的人。此外,由于答案解决了问题,请将其标记为已回答。 –