如何在spark中排除csv列?

时间:2018-04-18 06:50:21

标签: apache-spark

Rdd由完整的csv条记录组成,无法找到从中排除特定colums的方法。

我尝试了drop()

例如CSV File由三个columns no,name and age组成。

现在我需要排除2列no和name

Val excluColumns='no,name'    
rdd.drop(excluColumns)

在代码中出现问题。

这是spark的新手,任何人都会指导我这样做。

EDIT-1

val cols="no,name"
val excluColumns= Seq(cols)
df.drop(excluColumns:_*)
  .show()

它导致转换问题。

2 个答案:

答案 0 :(得分:1)

  StringWriter sw = new StringWriter();
                sw.WriteLine("\"Id No\",\"Customer Name\",\"Customer Mobile No\",\"Customer BusinessZone\"");
                Response.ClearContent();
                Response.AddHeader("content-disposition", "attachment;filename=Security_User.csv");
                Response.ContentType = "text/csv";
                foreach (var user in _securityUserService.GetAllCustomer())
                {
                    sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\"",
                                               user.Id,
                                               user.FullName,
                                               user.Phone,
                                               user.BusinessZones.Name));
                }

                Response.Write(sw.ToString());

                Response.End();
            }

答案 1 :(得分:1)

RDD没有列名所以您必须将其作为数据框读取并使用drop (假设您在文件中有标题)

该文件应为

no,name,age
1,bill,23
2,charles,24
3,gates,45

您将其作为

读取到数据框
val df = sqlContext.read.format("com.databricks.spark.csv").option("header", true).load("File.csv")

应该给你

+---+-------+---+
|no |name   |age|
+---+-------+---+
|1  |bill   |23 |
|2  |charles|24 |
|3  |gates  |45 |
+---+-------+---+

然后你可以创建要删除的列序列并使用它如下

val excluColumns= "no,name".split(",")
df.drop(excluColumns:_*)
  .show()

这应该只为您提供年龄栏

+---+
|age|
+---+
| 23|
| 24|
| 45|
+---+
相关问题