简体   繁体   中英

Count total values in each row of dataframe using pyspark

I have a column in a data frame that has a list of dates separated by commas on each row. I want to create a new column called date_count that contains the number of dates per row. I tried using pandas but I want to implement this in pyspark and I am also new to spark.

df['date_count'] = 0
    for index in df.index.tolist():
        for i in (df.loc[[index],'date']):
            date_list = i.split(",")
            df.loc[[index],'date_count'] = len(date_list)

Below is my pyspark code for this:

values = [
  (1,"2019-10-11, 2019-10-12, 2019-10-13, 2019-10-14, 2019-10-15"),
  (2,"2019-11-11, 2019-11-12, 2019-11-17, 2019-11-18")
  ]

rdd = sc.parallelize(values)
schema = StructType([
    StructField("id", IntegerType(), True),StructField("dates", StringType(), True)
])

data = spark.createDataFrame(rdd, schema)

data.createOrReplaceTempView("data")
spark.sql("""select id, 
                    dates, 
                    size(split(dates, ",")) as date_count 
              from data""").show(20,False)

Result:

+---+----------------------------------------------------------+----------+
|id |dates                                                     |date_count|
+---+----------------------------------------------------------+----------+
|1  |2019-10-11, 2019-10-12, 2019-10-13, 2019-10-14, 2019-10-15|5         |
|2  |2019-11-11, 2019-11-12, 2019-11-17, 2019-11-18            |4         |
+---+----------------------------------------------------------+----------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM