将数据转化为rdd并分析
Transform data into rdd and analyze
我是 spark 的新手,有以下 csv 格式的数据,我想将其转换为正确的格式。
没有 header
的 Csv 文件
Student_name=abc, student_grades=A, Student_gender=female
Student_name=Xyz, student_grades=B, Student_gender=male
现在我想把它放在 rdd 中创建 header
Student_Name student_grades student_gender
abc A female
Xyz B male
我还想获得成绩为 A、B 和 C 的学生列表
您可以做的是从文件的第一行推断模式,然后相应地转换数据帧,即:
- 从行值中删除列名。
- 重命名列
这里是你如何做到的。首先,让我们从文件中读取数据并显示它。
// the options are here to get rid of potential spaces around the ",".
val df = spark.read
.option("ignoreTrailingWhiteSpace", true)
.option("ignoreLeadingWhiteSpace", true)
.csv("path/your_file.csv")
df.show(false)
+----------------+----------------+---------------------+
|_c0 |_c1 |_c2 |
+----------------+----------------+---------------------+
|Student_name=abc|student_grades=A|Student_gender=female|
|Student_name=Xyz|student_grades=B|Student_gender=male |
+----------------+----------------+---------------------+
然后,我们使用数据帧的第一行提取默认名称和新名称之间的映射。
val row0 = df.head
val cols = df
.columns
.map(c => c -> row0.getAs[String](c).split("=").head )
最后,我们去掉了在“=”上带有 split
的列的名称,并使用我们的映射重命名了这些列:
val new_df = df
.select(cols.map{ case (old_name, new_name) =>
split(col(old_name), "=")(1) as new_name
} : _*)
new_df.show(false)
+------------+--------------+--------------+
|Student_name|student_grades|Student_gender|
+------------+--------------+--------------+
|abc |A |female |
|Xyz |B |male |
+------------+--------------+--------------+
我是 spark 的新手,有以下 csv 格式的数据,我想将其转换为正确的格式。
没有 header
的 Csv 文件Student_name=abc, student_grades=A, Student_gender=female
Student_name=Xyz, student_grades=B, Student_gender=male
现在我想把它放在 rdd 中创建 header
Student_Name student_grades student_gender
abc A female
Xyz B male
我还想获得成绩为 A、B 和 C 的学生列表
您可以做的是从文件的第一行推断模式,然后相应地转换数据帧,即:
- 从行值中删除列名。
- 重命名列
这里是你如何做到的。首先,让我们从文件中读取数据并显示它。
// the options are here to get rid of potential spaces around the ",".
val df = spark.read
.option("ignoreTrailingWhiteSpace", true)
.option("ignoreLeadingWhiteSpace", true)
.csv("path/your_file.csv")
df.show(false)
+----------------+----------------+---------------------+
|_c0 |_c1 |_c2 |
+----------------+----------------+---------------------+
|Student_name=abc|student_grades=A|Student_gender=female|
|Student_name=Xyz|student_grades=B|Student_gender=male |
+----------------+----------------+---------------------+
然后,我们使用数据帧的第一行提取默认名称和新名称之间的映射。
val row0 = df.head
val cols = df
.columns
.map(c => c -> row0.getAs[String](c).split("=").head )
最后,我们去掉了在“=”上带有 split
的列的名称,并使用我们的映射重命名了这些列:
val new_df = df
.select(cols.map{ case (old_name, new_name) =>
split(col(old_name), "=")(1) as new_name
} : _*)
new_df.show(false)
+------------+--------------+--------------+
|Student_name|student_grades|Student_gender|
+------------+--------------+--------------+
|abc |A |female |
|Xyz |B |male |
+------------+--------------+--------------+