Issue
I am trying to get the column names and the data types of each column from the original Dataframe "User_df" into their own columns where the values of the columns are the column names and datatypes respectively.
I have 88 Columns and about 9500 Rows.
The below code works when I try to create a Dataframe with one column ("ColumnDataTypes") but not when I try to do it for both columns:
col_types = User_df.dtypes
col_types2, col_types3 = [items[:] for items in zip(*col_types)]
rdd_col_names = sc.parallelize(col_types2)
rdd_col_types = sc.parallelize(col_types3)
row_rdd_col_names = rdd_col_names.map(lambda x: Row(x))
row_rdd_col_types = rdd_col_types.map(lambda x: Row(x))
data1 = row_rdd_col_names
data2 = row_rdd_col_types
schema3 = StructType([StructField("ColumnDataTypes", StringType(), True)])
new_dataframe = sqlContext.createDataFrame(data2, schema3)
new_dataframe.show()
+---------------+
|ColumnDataTypes|
+---------------+
|string |
|date |
|int |
|int |
|int |
|int |
|int |
|double |
|double |
|double |
|double |
|int |
|int |
|int |
|int |
|int |
|int |
|int |
|double |
|int |
|double |
|int |
|int |
|double |
|int |
|double |
|int |
|int |
|double |
|double |
|double |
|double |
|double |
|double |
|double |
|int |
|int |
|int |
|int |
|double |
|int |
|double |
|int |
|int |
|int |
|double |
|double |
|int |
|double |
|int |
|double |
|double |
|int |
|double |
|double |
|int |
|double |
|double |
|int |
|double |
|double |
|int |
|double |
|double |
|int |
|string |
|int |
|string |
|string |
|int |
|string |
|string |
|string |
|double |
|string |
|string |
|string |
|string |
|int |
|string |
|boolean |
|string |
|int |
|boolean |
|boolean |
|string |
|string |
|string |
+---------------+
Below is the code to get both columns into one dataframe but it gives me an error:
# Get each Columns name and data type from the original Dataframe
"User_df":
col_types = User_df.dtypes
col_types2, col_types3 = [items[:] for items in zip(*col_types)]
rdd_col_names = sc.parallelize(col_types2)
rdd_col_types = sc.parallelize(col_types3)
row_rdd_col_names = rdd_col_names.map(lambda x: Row(x))
row_rdd_col_types = rdd_col_types.map(lambda x: Row(x))
data = [[row_rdd_col_names], [row_rdd_col_types]]
schema = StructType([StructField("ColumnNames", StringType(), True),
StructField("ColumnDataTypes", StringType(), True)
])
new_dataframe = sqlContext.createDataFrame(data, schema)
display(new_dataframe)
This is the error the above code gives me:
ValueError Traceback (most recent call last)
/tmp/ipykernel_16479/193552006.py in <module>
26 # StructType([StructField("ColumnDataTypes", StringType(), True)])
27
---> 28 new_dff0 = sqlContext.createDataFrame(data, schema)
29
30
/opt/spark/python/lib/pyspark.zip/pyspark/sql/context.py in createDataFrame(self, data, schema, samplingRatio, verifySchema)
367 Py4JJavaError: ...
368 """
--> 369 return self.sparkSession.createDataFrame(data, schema, samplingRatio, verifySchema)
370
371 def registerDataFrameAsTable(self, df, tableName):
/opt/spark/python/lib/pyspark.zip/pyspark/sql/session.py in createDataFrame(self, data, schema, samplingRatio, verifySchema)
673 return super(SparkSession, self).createDataFrame(
674 data, schema, samplingRatio, verifySchema)
--> 675 return self._create_dataframe(data, schema, samplingRatio, verifySchema)
676
677 def _create_dataframe(self, data, schema, samplingRatio, verifySchema):
/opt/spark/python/lib/pyspark.zip/pyspark/sql/session.py in _create_dataframe(self, data, schema, samplingRatio, verifySchema)
698 rdd, schema = self._createFromRDD(data.map(prepare), schema, samplingRatio)
699 else:
--> 700 rdd, schema = self._createFromLocal(map(prepare, data), schema)
701 jrdd = self._jvm.SerDeUtil.toJavaArray(rdd._to_java_object_rdd())
702 jdf = self._jsparkSession.applySchemaToPythonRDD(jrdd.rdd(), schema.json())
/opt/spark/python/lib/pyspark.zip/pyspark/sql/session.py in _createFromLocal(self, data, schema)
507 # make sure data could consumed multiple times
508 if not isinstance(data, list):
--> 509 data = list(data)
510
511 if schema is None or isinstance(schema, (list, tuple)):
/opt/spark/python/lib/pyspark.zip/pyspark/sql/session.py in prepare(obj)
680
681 def prepare(obj):
--> 682 verify_func(obj)
683 return obj
684 elif isinstance(schema, DataType):
/opt/spark/python/lib/pyspark.zip/pyspark/sql/types.py in verify(obj)
1407 def verify(obj):
1408 if not verify_nullability(obj):
-> 1409 verify_value(obj)
1410
1411 return verify
/opt/spark/python/lib/pyspark.zip/pyspark/sql/types.py in verify_struct(obj)
1384 elif isinstance(obj, (tuple, list)):
1385 if len(obj) != len(verifiers):
-> 1386 raise ValueError(
1387 new_msg("Length of object (%d) does not match with "
1388 "length of fields (%d)" % (len(obj), len(verifiers))))
ValueError: Length of object (1) does not match with length of fields (2)
I'm not understanding why it gives me "ValueError: Length of object (1) does not match with length of fields (2)" because I have specified 2 columns and looped through the values of each of the two columns.
When I put the variables "row_rdd_col_names" and "row_rdd_col_types" in the "data" variable in Parenthesis instead of brackets I get the two columns I want but I just get two rows for each column that says "undefined" if I use the "display()" function in Synapse Notebooks and "null" if I use ".show()", still not sure what I'm doing wrong:
# Get each Columns name and data type from the original Dataframe
"User_df":
col_types = User_df.dtypes
col_types2, col_types3 = [items[:] for items in zip(*col_types)]
rdd_col_names = sc.parallelize(col_types2)
rdd_col_types = sc.parallelize(col_types3)
row_rdd_col_names = rdd_col_names.map(lambda x: Row(x))
row_rdd_col_types = rdd_col_types.map(lambda x: Row(x))
data = [(row_rdd_col_names), (row_rdd_col_types)]
schema = StructType([StructField("ColumnNames", StringType(), True),
StructField("ColumnDataTypes", StringType(), True)
])
new_dataframe = sqlContext.createDataFrame(data, schema)
new_dataframe.show()
# The above code gives the following Result:
+-----------+---------------+
|ColumnNames|ColumnDataTypes|
+-----------+---------------+
| null| null|
| null| null|
+-----------+---------------+
Solution
If you want the name and type of a spark dataframe as a spark dataframe, a single line code like the following would work.
For a spark dataframe data_sdf, the .dtypes will generate a list of tuples for column names and their types.
data_sdf.dtypes
# [('event_id', 'string'),
# ('cust_id', 'string'),
# ('event_typ', 'string'),
# ('event_ts', 'bigint'),
# ('item_id', 'bigint'),
# ('next_event_typ', 'string'),
# ('prev_event_typ', 'string')]
Which means it can be directly converted to a spark dataframe.
spark.sparkContext.parallelize(data_sdf.dtypes).toDF(['column_name', 'column_datatype']). \
show()
# +--------------+---------------+
# | column_name|column_datatype|
# +--------------+---------------+
# | event_id| string|
# | cust_id| string|
# | event_typ| string|
# | event_ts| bigint|
# | item_id| bigint|
# |next_event_typ| string|
# |prev_event_typ| string|
# +--------------+---------------+
You can also use createDataFrame() that will result in the same output.
spark.createDataFrame(data_sdf.dtypes, 'column_name string, column_datatype string'). \
show()
Answered By - samkart Answer Checked By - Cary Denson (sql.easybugfix Admin)
Post a Comment
Post a Comment