Created
May 10, 2022 12:22
-
-
Save thangarajan8/68640b9cc0958fc925c68d9777f05f63 to your computer and use it in GitHub Desktop.
pandas to spark data frame.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pyspark.sql.types import * | |
# Auxiliar functions | |
# Pandas Types -> Sparks Types | |
def equivalent_type(f): | |
if f == 'datetime64[ns]': return DateType() | |
elif f == 'int64': return LongType() | |
elif f == 'int32': return IntegerType() | |
elif f == 'float64': return FloatType() | |
else: return StringType() | |
def define_structure(string, format_type): | |
try: typo = equivalent_type(format_type) | |
except: typo = StringType() | |
return StructField(string, typo) | |
#Given pandas dataframe, it will return a spark's dataframe | |
def pandas_to_spark(df_pandas): | |
columns = list(df_pandas.columns) | |
types = list(df_pandas.dtypes) | |
struct_list = [] | |
for column, typo in zip(columns, types): | |
struct_list.append(define_structure(column, typo)) | |
p_schema = StructType(struct_list) | |
return sqlContext.createDataFrame(df_pandas, p_schema) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment