0

The following will provide the default column name given the query

%python
df = sql("select last_day(add_months(current_date(),-1))")
display(df)

enter image description here

Can someone let me know how to change the column rename the column to say 'newname', instead of the default name last_day(add_months(current_date(), -1))

I've tried

%python
df = sql("select last_day(add_months(current_date(),-1)) as 'newname'")

But it didn't work

Patterson
  • 1,927
  • 1
  • 19
  • 56
  • 1
    removing the single quotes in sql query should fix the error, `sql("select last_day(add_months(current_date(),-1)) as newname")` – ClumsyPuffin Jun 25 '23 at 11:27

2 Answers2

0

PySpark dataframes have withColumnRenamed function

You can use it as

df = df.withColumnRenamed('column_name', 'new_column_name')
Zero
  • 1,807
  • 1
  • 6
  • 17
0

You can try anyone from below:

df = df.selectExpr("add_months(current_date(),-1)) as newname")

sqlContext.registerDataFrameAsTable(df, "Table")
new_name_df = sqlContext.sql("SELECT add_months(current_date(),-1)) AS newname from Table")
new_name_df.show()

from pyspark.sql.functions import col
df = df.select(col("add_months(current_date(),-1))").alias("newname"))
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44