Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How divide or multiply every non-string columns of a PySpark dataframe with a float constant?

My input dataframe looks like the below

from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Basics").getOrCreate()

df=spark.createDataFrame(data=[('Alice',4.300,None),('Bob',float('nan'),897)],schema=['name','High','Low'])

+-----+----+----+
| name|High| Low|
+-----+----+----+
|Alice| 4.3|null|
|  Bob| NaN| 897|
+-----+----+----+

Expected Output if divided by 10.0

+-----+----+----+
| name|High| Low|
+-----+----+----+
|Alice| 0.43|null|
|  Bob| NaN| 89.7|
+-----+----+----+
like image 494
GeorgeOfTheRF Avatar asked Jun 28 '17 16:06

GeorgeOfTheRF


2 Answers

I don't know about any library function that could do this, but this snippet seems to do job just fine:

CONSTANT = 10.0

for field in df.schema.fields:
    if str(field.dataType) in ['DoubleType', 'FloatType', 'LongType', 'IntegerType', 'DecimalType']:
        name = str(field.name)
        df = df.withColumn(name, col(name)/CONSTANT)


df.show()

outputs:

+-----+----+----+
| name|High| Low|
+-----+----+----+
|Alice|0.43|null|
|  Bob| NaN|89.7|
+-----+----+----+
like image 74
Konrad Kostrzewa Avatar answered Oct 19 '22 23:10

Konrad Kostrzewa


The below code should solve your problem in a time efficient manner

from pyspark.sql.functions import col

allowed_types = ['DoubleType', 'FloatType', 'LongType', 'IntegerType', 'DecimalType']

df = df.select(*[(col(field.name)/10).name(field.name) if str(field.dataType) in allowed_types else col(field.name) for field in df.schema.fields]

Using "withColumn" iteratively might not be a good idea when the number of columns is large.
This is because PySpark dataframes are immutable, so essentially we will be creating a new DataFrame for each column casted using withColumn, which will be a very slow process.

This is where the above code comes in handy.

like image 31
bhavi Avatar answered Oct 20 '22 00:10

bhavi