Creating a DataFrame from RDD while specifying DateType() in schema2019 Community Moderator ElectionHow to remove items from a list while iterating?Delete column from pandas DataFrame by column nameSelect rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headersDifference between DataFrame, Dataset, and RDD in SparkConvert json string to modified RDDSpark SQL(v2.0) UDAF in Scala returns empty stringEnforcing a schema on RDD while converting them to DataFrameHow do I apply schema with nullable = false to json readingpyspark load csv file into dataframe using a schema

What is the likely impact of grounding an entire aircraft series?

In the late 1940’s to early 1950’s what technology was available that could melt a LOT of ice?

How much stiffer are 23c tires over 28c?

show this identity with trigometric

Solving "Resistance between two nodes on a grid" problem in Mathematica

Why is this plane circling around the Lucknow airport every day?

Can you reject a postdoc offer after the PI has paid a large sum for flights/accommodation for your visit?

Make a transparent 448*448 image

Why doesn't this Google Translate ad use the word "Translation" instead of "Translate"?

What are some noteworthy "mic-drop" moments in math?

They call me Inspector Morse

Do f-stop and exposure time perfectly cancel?

PTIJ: Why can't I eat anything?

String reversal in Python

Virginia employer terminated employee and wants signing bonus returned

Finding algorithms of QGIS commands?

Should QA ask requirements to developers?

How does airport security verify that you can carry a battery bank over 100 Wh?

Why is there a voltage between the mains ground and my radiator?

How do anti-virus programs start at Windows boot?

Placing subfig vertically

What to do when during a meeting client people start to fight (even physically) with each others?

Can't find the Shader/UVs tab

How to pass a string to a command that expects a file?



Creating a DataFrame from RDD while specifying DateType() in schema



2019 Community Moderator ElectionHow to remove items from a list while iterating?Delete column from pandas DataFrame by column nameSelect rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headersDifference between DataFrame, Dataset, and RDD in SparkConvert json string to modified RDDSpark SQL(v2.0) UDAF in Scala returns empty stringEnforcing a schema on RDD while converting them to DataFrameHow do I apply schema with nullable = false to json readingpyspark load csv file into dataframe using a schema










1















I am creating a DataFrame from RDD and one of the value is a date. I don't know how to specify DateType() in schema.



Let me illustrate the problem at hand -



One way we can load the date into the DataFrame is by first specifying it as string and converting it to proper date using to_date() function.



from pyspark.sql.types import Row, StructType, StructField, StringType, IntegerType, DateType
from pyspark.sql.functions import col, to_date
values=sc.parallelize([(3,'2012-02-02'),(5,'2018-08-08')])
rdd= values.map(lambda t: Row(A=t[0],date=t[1]))

# Importing date as String in Schema
schema = StructType([StructField('A', IntegerType(), True), StructField('date', StringType(), True)])
df = sqlContext.createDataFrame(rdd, schema)

# Finally converting the string into date using to_date() function.
df = df.withColumn('date',to_date(col('date'), 'yyyy-MM-dd'))
df.show()
+---+----------+
| A| date|
+---+----------+
| 3|2012-02-02|
| 5|2018-08-08|
+---+----------+

df.printSchema()
root
|-- A: integer (nullable = true)
|-- date: date (nullable = true)


Is there a way, where we could use DateType() in the schema and avoid having to convert string to date explicitly?



Something like this -



values=sc.parallelize([(3,'2012-02-02'),(5,'2018-08-08')])
rdd= values.map(lambda t: Row(A=t[0],date=t[1]))
# Somewhere we would need to specify date format 'yyyy-MM-dd' too, don't know where though.
schema = StructType([StructField('A', DateType(), True), StructField('date', DateType(), True)])


UPDATE: As suggested by @user10465355, following code works -



import datetime
schema = StructType([
StructField('A', IntegerType(), True),
StructField('date', DateType(), True)
])
rdd= values.map(lambda t: Row(A=t[0],date=datetime.datetime.strptime(t[1], "%Y-%m-%d")))
df = sqlContext.createDataFrame(rdd, schema)
df.show()
+---+----------+
| A| date|
+---+----------+
| 3|2012-02-02|
| 5|2018-08-08|
+---+----------+
df.printSchema()
root
|-- A: integer (nullable = true)
|-- date: date (nullable = true)









share|improve this question




























    1















    I am creating a DataFrame from RDD and one of the value is a date. I don't know how to specify DateType() in schema.



    Let me illustrate the problem at hand -



    One way we can load the date into the DataFrame is by first specifying it as string and converting it to proper date using to_date() function.



    from pyspark.sql.types import Row, StructType, StructField, StringType, IntegerType, DateType
    from pyspark.sql.functions import col, to_date
    values=sc.parallelize([(3,'2012-02-02'),(5,'2018-08-08')])
    rdd= values.map(lambda t: Row(A=t[0],date=t[1]))

    # Importing date as String in Schema
    schema = StructType([StructField('A', IntegerType(), True), StructField('date', StringType(), True)])
    df = sqlContext.createDataFrame(rdd, schema)

    # Finally converting the string into date using to_date() function.
    df = df.withColumn('date',to_date(col('date'), 'yyyy-MM-dd'))
    df.show()
    +---+----------+
    | A| date|
    +---+----------+
    | 3|2012-02-02|
    | 5|2018-08-08|
    +---+----------+

    df.printSchema()
    root
    |-- A: integer (nullable = true)
    |-- date: date (nullable = true)


    Is there a way, where we could use DateType() in the schema and avoid having to convert string to date explicitly?



    Something like this -



    values=sc.parallelize([(3,'2012-02-02'),(5,'2018-08-08')])
    rdd= values.map(lambda t: Row(A=t[0],date=t[1]))
    # Somewhere we would need to specify date format 'yyyy-MM-dd' too, don't know where though.
    schema = StructType([StructField('A', DateType(), True), StructField('date', DateType(), True)])


    UPDATE: As suggested by @user10465355, following code works -



    import datetime
    schema = StructType([
    StructField('A', IntegerType(), True),
    StructField('date', DateType(), True)
    ])
    rdd= values.map(lambda t: Row(A=t[0],date=datetime.datetime.strptime(t[1], "%Y-%m-%d")))
    df = sqlContext.createDataFrame(rdd, schema)
    df.show()
    +---+----------+
    | A| date|
    +---+----------+
    | 3|2012-02-02|
    | 5|2018-08-08|
    +---+----------+
    df.printSchema()
    root
    |-- A: integer (nullable = true)
    |-- date: date (nullable = true)









    share|improve this question


























      1












      1








      1








      I am creating a DataFrame from RDD and one of the value is a date. I don't know how to specify DateType() in schema.



      Let me illustrate the problem at hand -



      One way we can load the date into the DataFrame is by first specifying it as string and converting it to proper date using to_date() function.



      from pyspark.sql.types import Row, StructType, StructField, StringType, IntegerType, DateType
      from pyspark.sql.functions import col, to_date
      values=sc.parallelize([(3,'2012-02-02'),(5,'2018-08-08')])
      rdd= values.map(lambda t: Row(A=t[0],date=t[1]))

      # Importing date as String in Schema
      schema = StructType([StructField('A', IntegerType(), True), StructField('date', StringType(), True)])
      df = sqlContext.createDataFrame(rdd, schema)

      # Finally converting the string into date using to_date() function.
      df = df.withColumn('date',to_date(col('date'), 'yyyy-MM-dd'))
      df.show()
      +---+----------+
      | A| date|
      +---+----------+
      | 3|2012-02-02|
      | 5|2018-08-08|
      +---+----------+

      df.printSchema()
      root
      |-- A: integer (nullable = true)
      |-- date: date (nullable = true)


      Is there a way, where we could use DateType() in the schema and avoid having to convert string to date explicitly?



      Something like this -



      values=sc.parallelize([(3,'2012-02-02'),(5,'2018-08-08')])
      rdd= values.map(lambda t: Row(A=t[0],date=t[1]))
      # Somewhere we would need to specify date format 'yyyy-MM-dd' too, don't know where though.
      schema = StructType([StructField('A', DateType(), True), StructField('date', DateType(), True)])


      UPDATE: As suggested by @user10465355, following code works -



      import datetime
      schema = StructType([
      StructField('A', IntegerType(), True),
      StructField('date', DateType(), True)
      ])
      rdd= values.map(lambda t: Row(A=t[0],date=datetime.datetime.strptime(t[1], "%Y-%m-%d")))
      df = sqlContext.createDataFrame(rdd, schema)
      df.show()
      +---+----------+
      | A| date|
      +---+----------+
      | 3|2012-02-02|
      | 5|2018-08-08|
      +---+----------+
      df.printSchema()
      root
      |-- A: integer (nullable = true)
      |-- date: date (nullable = true)









      share|improve this question
















      I am creating a DataFrame from RDD and one of the value is a date. I don't know how to specify DateType() in schema.



      Let me illustrate the problem at hand -



      One way we can load the date into the DataFrame is by first specifying it as string and converting it to proper date using to_date() function.



      from pyspark.sql.types import Row, StructType, StructField, StringType, IntegerType, DateType
      from pyspark.sql.functions import col, to_date
      values=sc.parallelize([(3,'2012-02-02'),(5,'2018-08-08')])
      rdd= values.map(lambda t: Row(A=t[0],date=t[1]))

      # Importing date as String in Schema
      schema = StructType([StructField('A', IntegerType(), True), StructField('date', StringType(), True)])
      df = sqlContext.createDataFrame(rdd, schema)

      # Finally converting the string into date using to_date() function.
      df = df.withColumn('date',to_date(col('date'), 'yyyy-MM-dd'))
      df.show()
      +---+----------+
      | A| date|
      +---+----------+
      | 3|2012-02-02|
      | 5|2018-08-08|
      +---+----------+

      df.printSchema()
      root
      |-- A: integer (nullable = true)
      |-- date: date (nullable = true)


      Is there a way, where we could use DateType() in the schema and avoid having to convert string to date explicitly?



      Something like this -



      values=sc.parallelize([(3,'2012-02-02'),(5,'2018-08-08')])
      rdd= values.map(lambda t: Row(A=t[0],date=t[1]))
      # Somewhere we would need to specify date format 'yyyy-MM-dd' too, don't know where though.
      schema = StructType([StructField('A', DateType(), True), StructField('date', DateType(), True)])


      UPDATE: As suggested by @user10465355, following code works -



      import datetime
      schema = StructType([
      StructField('A', IntegerType(), True),
      StructField('date', DateType(), True)
      ])
      rdd= values.map(lambda t: Row(A=t[0],date=datetime.datetime.strptime(t[1], "%Y-%m-%d")))
      df = sqlContext.createDataFrame(rdd, schema)
      df.show()
      +---+----------+
      | A| date|
      +---+----------+
      | 3|2012-02-02|
      | 5|2018-08-08|
      +---+----------+
      df.printSchema()
      root
      |-- A: integer (nullable = true)
      |-- date: date (nullable = true)






      python apache-spark pyspark






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 7 at 13:05







      cph_sto

















      asked Mar 7 at 7:51









      cph_stocph_sto

      2,3282422




      2,3282422






















          1 Answer
          1






          active

          oldest

          votes


















          3














          Long story short, schema used with RDD of external object is not intended to be used that way - declared types should reflect the actual state of the data, not the desired one.



          In other words to allow:



          schema = StructType([
          StructField('A', IntegerType(), True),
          StructField('date', DateType(), True)
          ])


          the data corresponding to date field should use datetime.date. So for example with your RDD[Tuple[int, str]]:



          import datetime

          spark.createDataFrame(
          # Since values from the question are just two element tuples
          # we can use mapValues to transform the "value"
          # but in general case you'll need map
          values.mapValues(datetime.date.fromisoformat),
          schema
          )


          The closest you can get to desired behavior is to convert data (RDD[Row]) with JSON reader, using dicts



          from pyspark.sql import Row

          spark.read.schema(schema).json(rdd.map(Row.asDict))


          or better explicit JSON dumps:



          import json
          spark.read.schema(schema).json(rdd.map(Row.asDict).map(json.dumps))


          but that's of course much more expensive than explicit casting, which BTW, is easy to automate in simple cases like the one you describe:



          from pyspark.sql.functions import col

          (spark
          .createDataFrame(values, ("a", "date"))
          .select([col(f.name).cast(f.dataType) for f in schema]))





          share|improve this answer

























          • Thank you so much for your efforts. Appreciated!! Your code, with slight modification, works :) I just made a post-update.

            – cph_sto
            Mar 7 at 13:06











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55038612%2fcreating-a-dataframe-from-rdd-while-specifying-datetype-in-schema%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          Long story short, schema used with RDD of external object is not intended to be used that way - declared types should reflect the actual state of the data, not the desired one.



          In other words to allow:



          schema = StructType([
          StructField('A', IntegerType(), True),
          StructField('date', DateType(), True)
          ])


          the data corresponding to date field should use datetime.date. So for example with your RDD[Tuple[int, str]]:



          import datetime

          spark.createDataFrame(
          # Since values from the question are just two element tuples
          # we can use mapValues to transform the "value"
          # but in general case you'll need map
          values.mapValues(datetime.date.fromisoformat),
          schema
          )


          The closest you can get to desired behavior is to convert data (RDD[Row]) with JSON reader, using dicts



          from pyspark.sql import Row

          spark.read.schema(schema).json(rdd.map(Row.asDict))


          or better explicit JSON dumps:



          import json
          spark.read.schema(schema).json(rdd.map(Row.asDict).map(json.dumps))


          but that's of course much more expensive than explicit casting, which BTW, is easy to automate in simple cases like the one you describe:



          from pyspark.sql.functions import col

          (spark
          .createDataFrame(values, ("a", "date"))
          .select([col(f.name).cast(f.dataType) for f in schema]))





          share|improve this answer

























          • Thank you so much for your efforts. Appreciated!! Your code, with slight modification, works :) I just made a post-update.

            – cph_sto
            Mar 7 at 13:06
















          3














          Long story short, schema used with RDD of external object is not intended to be used that way - declared types should reflect the actual state of the data, not the desired one.



          In other words to allow:



          schema = StructType([
          StructField('A', IntegerType(), True),
          StructField('date', DateType(), True)
          ])


          the data corresponding to date field should use datetime.date. So for example with your RDD[Tuple[int, str]]:



          import datetime

          spark.createDataFrame(
          # Since values from the question are just two element tuples
          # we can use mapValues to transform the "value"
          # but in general case you'll need map
          values.mapValues(datetime.date.fromisoformat),
          schema
          )


          The closest you can get to desired behavior is to convert data (RDD[Row]) with JSON reader, using dicts



          from pyspark.sql import Row

          spark.read.schema(schema).json(rdd.map(Row.asDict))


          or better explicit JSON dumps:



          import json
          spark.read.schema(schema).json(rdd.map(Row.asDict).map(json.dumps))


          but that's of course much more expensive than explicit casting, which BTW, is easy to automate in simple cases like the one you describe:



          from pyspark.sql.functions import col

          (spark
          .createDataFrame(values, ("a", "date"))
          .select([col(f.name).cast(f.dataType) for f in schema]))





          share|improve this answer

























          • Thank you so much for your efforts. Appreciated!! Your code, with slight modification, works :) I just made a post-update.

            – cph_sto
            Mar 7 at 13:06














          3












          3








          3







          Long story short, schema used with RDD of external object is not intended to be used that way - declared types should reflect the actual state of the data, not the desired one.



          In other words to allow:



          schema = StructType([
          StructField('A', IntegerType(), True),
          StructField('date', DateType(), True)
          ])


          the data corresponding to date field should use datetime.date. So for example with your RDD[Tuple[int, str]]:



          import datetime

          spark.createDataFrame(
          # Since values from the question are just two element tuples
          # we can use mapValues to transform the "value"
          # but in general case you'll need map
          values.mapValues(datetime.date.fromisoformat),
          schema
          )


          The closest you can get to desired behavior is to convert data (RDD[Row]) with JSON reader, using dicts



          from pyspark.sql import Row

          spark.read.schema(schema).json(rdd.map(Row.asDict))


          or better explicit JSON dumps:



          import json
          spark.read.schema(schema).json(rdd.map(Row.asDict).map(json.dumps))


          but that's of course much more expensive than explicit casting, which BTW, is easy to automate in simple cases like the one you describe:



          from pyspark.sql.functions import col

          (spark
          .createDataFrame(values, ("a", "date"))
          .select([col(f.name).cast(f.dataType) for f in schema]))





          share|improve this answer















          Long story short, schema used with RDD of external object is not intended to be used that way - declared types should reflect the actual state of the data, not the desired one.



          In other words to allow:



          schema = StructType([
          StructField('A', IntegerType(), True),
          StructField('date', DateType(), True)
          ])


          the data corresponding to date field should use datetime.date. So for example with your RDD[Tuple[int, str]]:



          import datetime

          spark.createDataFrame(
          # Since values from the question are just two element tuples
          # we can use mapValues to transform the "value"
          # but in general case you'll need map
          values.mapValues(datetime.date.fromisoformat),
          schema
          )


          The closest you can get to desired behavior is to convert data (RDD[Row]) with JSON reader, using dicts



          from pyspark.sql import Row

          spark.read.schema(schema).json(rdd.map(Row.asDict))


          or better explicit JSON dumps:



          import json
          spark.read.schema(schema).json(rdd.map(Row.asDict).map(json.dumps))


          but that's of course much more expensive than explicit casting, which BTW, is easy to automate in simple cases like the one you describe:



          from pyspark.sql.functions import col

          (spark
          .createDataFrame(values, ("a", "date"))
          .select([col(f.name).cast(f.dataType) for f in schema]))






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 7 at 13:13

























          answered Mar 7 at 10:48









          user10465355user10465355

          2,1172419




          2,1172419












          • Thank you so much for your efforts. Appreciated!! Your code, with slight modification, works :) I just made a post-update.

            – cph_sto
            Mar 7 at 13:06


















          • Thank you so much for your efforts. Appreciated!! Your code, with slight modification, works :) I just made a post-update.

            – cph_sto
            Mar 7 at 13:06

















          Thank you so much for your efforts. Appreciated!! Your code, with slight modification, works :) I just made a post-update.

          – cph_sto
          Mar 7 at 13:06






          Thank you so much for your efforts. Appreciated!! Your code, with slight modification, works :) I just made a post-update.

          – cph_sto
          Mar 7 at 13:06




















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid …


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55038612%2fcreating-a-dataframe-from-rdd-while-specifying-datetype-in-schema%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

          Posting a File and Associated Data to a RESTful WebService preferably as JSON2019 Community Moderator ElectionREST URI convention - Singular or plural name of resource while creating itUploading both data and files in one form using Ajax?How do I upload a file with metadata using a REST web service?REST API - file (ie images) processing - best practicesSpring: JSON data and file in the same requestREST API Put large dataPosting a file and JSON data to Spring rest serviceRESTful Web Service Upload/Download Large Data With JSONREST API Design sending JSON data and a file to the api in same requestPost JSONArray to REST servicePUT vs. POST in RESTParsing values from a JSON file?JavaScript/jQuery to download file via POST with JSON dataHow do I upload a file with metadata using a REST web service?How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?Separate REST JSON API server and client?what's the correct way to send a file from REST web service to client?How do I write JSON data to a file?What is “406-Not Acceptable Response” in HTTP?REST API - file (ie images) processing - best practices

          How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page