Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 16 additions & 8 deletions sql/core/src/main/scala/org/apache/spark/sql/DataFrame.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1241,16 +1241,24 @@ class DataFrame private[sql](
* @since 1.4.0
*/
def drop(colName: String): DataFrame = {
drop(Seq(colName) : _*)
}

/**
* Returns a new [[DataFrame]] with columns dropped.
* This is a no-op if schema doesn't contain column name(s).
* @group dfops
* @since 1.6.0
*/
@scala.annotation.varargs
def drop(colNames: String*): DataFrame = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would need a varargs annotation and I don't think that we should duplicate the column resolution logic. Otherwise it might fall out of sync.

val resolver = sqlContext.analyzer.resolver
val shouldDrop = schema.exists(f => resolver(f.name, colName))
if (shouldDrop) {
val colsAfterDrop = schema.filter { field =>
val name = field.name
!resolver(name, colName)
}.map(f => Column(f.name))
select(colsAfterDrop : _*)
} else {
val remainingCols =
schema.filter(f => colNames.forall(n => !resolver(f.name, n))).map(f => Column(f.name))
if (remainingCols.size == this.schema.size) {
this
} else {
this.select(remainingCols: _*)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,13 @@ class DataFrameSuite extends QueryTest with SharedSQLContext {
assert(df.schema.map(_.name) === Seq("value"))
}

test("drop columns using drop") {
val src = Seq((0, 2, 3)).toDF("a", "b", "c")
val df = src.drop("a", "b")
checkAnswer(df, Row(3))
assert(df.schema.map(_.name) === Seq("c"))
}

test("drop unknown column (no-op)") {
val df = testData.drop("random")
checkAnswer(
Expand Down