import pandas as pd
from pyspark.sql.types import (
    StructField, StructType, StringType, IntegerType,
    LongType, DoubleType, TimestampType
)

def equivalent_type(f):
    if f == 'datetime64[ns]': return TimestampType()
    elif f == 'int64': return LongType()
    elif f == 'int32': return IntegerType()
    elif f == 'float64': return DoubleType()
    else: return StringType()
    
def define_structure(string, format_type):
    try: typo = equivalent_type(format_type)
    except: typo = StringType()
    return StructField(string, typo)
  
def pandas_to_spark(spark, pandas_df):
    """
    Converts a Pandas DataFrame to a Spark DataFrame with inferred schema.

    Parameters:
    -----------
    pandas_df (pd.DataFrame): The input pandas DataFrame.

    Returns:
    -----------
    DataFrame: A Spark DataFrame with schema inferred from pandas DataFrame.
    
    """
    
    columns = list(pandas_df.columns)
    types = list(pandas_df.dtypes)
    struct_list = [define_structure(col, dtype) for col, dtype in zip(columns, types)]
    p_schema = StructType(struct_list)
    return spark.createDataFrame(pandas_df, schema=p_schema)