Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPARK-46260][PYTHON][SQL] DataFrame.withColumnsRenamed should respect the dict ordering #44177

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
13 changes: 12 additions & 1 deletion python/pyspark/sql/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -6272,7 +6272,18 @@ def withColumnsRenamed(self, colsMap: Dict[str, str]) -> "DataFrame":
message_parameters={"arg_name": "colsMap", "arg_type": type(colsMap).__name__},
)

return DataFrame(self._jdf.withColumnsRenamed(colsMap), self.sparkSession)
col_names: List[str] = []
new_col_names: List[str] = []
for k, v in colsMap.items():
col_names.append(k)
new_col_names.append(v)

return DataFrame(
self._jdf.withColumnsRenamed(
_to_seq(self._sc, col_names), _to_seq(self._sc, new_col_names)
),
self.sparkSession,
)

def withMetadata(self, columnName: str, metadata: Dict[str, Any]) -> "DataFrame":
"""Returns a new :class:`DataFrame` by updating an existing column with metadata.
Expand Down
5 changes: 5 additions & 0 deletions python/pyspark/sql/tests/connect/test_parity_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ def test_to_pandas_from_mixed_dataframe(self):
def test_toDF_with_string(self):
super().test_toDF_with_string()

# TODO(SPARK-46260): DataFrame.withColumnsRenamed should respect the dict ordering
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I am hitting a weird proto issue, will fix it in a separate pr

@unittest.skip("Fails in Spark Connect, should enable.")
def test_ordering_of_with_columns_renamed(self):
super().test_ordering_of_with_columns_renamed()


if __name__ == "__main__":
import unittest
Expand Down
9 changes: 9 additions & 0 deletions python/pyspark/sql/tests/test_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,15 @@ def test_with_columns_renamed(self):
message_parameters={"arg_name": "colsMap", "arg_type": "tuple"},
)

def test_ordering_of_with_columns_renamed(self):
df = self.spark.range(10)

df1 = df.withColumnsRenamed({"id": "a", "a": "b"})
self.assertEqual(df1.columns, ["b"])

df2 = df.withColumnsRenamed({"a": "b", "id": "a"})
self.assertEqual(df2.columns, ["a"])

def test_drop_duplicates(self):
# SPARK-36034 test that drop duplicates throws a type error when in correct type provided
df = self.spark.createDataFrame([("Alice", 50), ("Alice", 60)], ["name", "age"])
Expand Down
27 changes: 19 additions & 8 deletions sql/core/src/main/scala/org/apache/spark/sql/Dataset.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2922,18 +2922,29 @@ class Dataset[T] private[sql](
*/
@throws[AnalysisException]
def withColumnsRenamed(colsMap: Map[String, String]): DataFrame = withOrigin {
Copy link
Member

Choose a reason for hiding this comment

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

Since we touch Dataset.scala, could you include [SQL] into the PR title?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

sounds good

val (colNames, newColNames) = colsMap.toSeq.unzip
withColumnsRenamed(colNames, newColNames)
}

private def withColumnsRenamed(
colNames: Seq[String],
newColNames: Seq[String]): DataFrame = withOrigin {
require(colNames.size == newColNames.size,
s"The size of existing column names: ${colNames.size} isn't equal to " +
s"the size of new column names: ${newColNames.size}")

val resolver = sparkSession.sessionState.analyzer.resolver
val output: Seq[NamedExpression] = queryExecution.analyzed.output

val projectList = colsMap.foldLeft(output) {
val projectList = colNames.zip(newColNames).foldLeft(output) {
Copy link
Member

Choose a reason for hiding this comment

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

We believe we need a Scala test case for this change, @zhengruifeng , because the PR description claims that Scala code ordering matters.

Copy link
Member

Choose a reason for hiding this comment

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

Could you add a new simple test case which fails without this change?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

this is a python issue.
to make sure the scala side is not changed, I add a scala test

case (attrs, (existingName, newName)) =>
attrs.map(attr =>
if (resolver(attr.name, existingName)) {
Alias(attr, newName)()
} else {
attr
}
)
attrs.map(attr =>
if (resolver(attr.name, existingName)) {
Alias(attr, newName)()
} else {
attr
}
)
}
SchemaUtils.checkColumnNameDuplication(
projectList.map(_.name),
Expand Down