concept column name in category pyspark

appears as: column name, column names, column names, column name
Data Analysis with Python and PySpark

This is an excerpt from Manning's book Data Analysis with Python and PySpark.

PySpark provides for each column in its data frame a dot notation that refers to the column. This is definitely the simplest way to select a column, as long as the name doesn’t contain any funny characters: PySpark will accept $!@# as a column name, but you won’t be able to use the dot notation for this column.

We can easily create a data frame from data in our program with the spark.createDataFrame function, as listing 4.2 shows. Our first parameter is the data itself. You can either provide a list of items (here a list of lists), a pandas data frame or a Resilient Distributed Dataset, which I cover in chapter 9. The second parameter is the schema of the data frame. chapter 6 covers the automatic and manual schema definitions in greater depth. In the meantime, passing a list of column names will make PySpark happy, while it infers the types (string, long, and double, respectively) of our columns. Visually, the data frame will look like figure 4.2, although much more simplified. The master node knows about the structure of the data frame, but the actual data is represented on the worker nodes. Each column maps to data stored somewhere on our cluster, managed by PySpark. We operate on the abstract structure and let the master delegate the work efficiently.

I’m a huge fan of having column names without capital letters. I’m a lazy typist, and pressing Shift all the time really adds up folks! I could potentially use withColumnRenamed() with a for loop over all the columns to rename all my columns in my data frame. The PySpark developers thought about this and offered a better way to rename all the columns of your data frame in one fell swoop. This relies on a method, toDF(), that returns a new data frame with the new columns. Just like drop(), toDF() takes a *cols so we’ll need to unpack our column names if they’re in a list. The code in listing 4.14 shows how you can rename all your columns to lower case in a single line using that method.

Listing 4.14. Batch lower-casing your data frame using the toDF() method
logs.toDF(*[x.lower() for x in logs.columns]).printSchema()

# root
#  |-- logserviceid: integer (nullable = true)
#  |-- logdate: timestamp (nullable = true)
#  |-- audiencetargetageid: integer (nullable = true)
#  |-- audiencetargetethnicid: integer (nullable = true)
#  |-- categoryid: integer (nullable = true)
#  [...]
#  |-- language2: integer (nullable = true)
#  |-- duration_seconds: integer (nullable = true)

If you look at the line of code, you can see that I’m not assigning the resulting data frame. I wanted to showcase the functionality, but since we have ancillary tables with column names that match, I wanted to avoid the trouble of lower-casing every column in every table.