PySpark toPandas 函数正在更改列类型

Его*_*еев 8 python pandas apache-spark pyspark

我有一个具有以下架构的 pyspark 数据框:

root
 |-- src_ip: integer (nullable = true)
 |-- dst_ip: integer (nullable = true)
Run Code Online (Sandbox Code Playgroud)

当通过 将此数据帧转换为 pandas 时toPandas(),列类型从 Spark 中的整数更改为 pandas 中的浮点数:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 9847 entries, 0 to 9846
Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   src_ip  9607 non-null   float64
 1   dst_ip  9789 non-null   float64
dtypes: float64(2)
memory usage: 154.0 KB
Run Code Online (Sandbox Code Playgroud)

有什么方法可以保留整数值,toPandas()或者我只能在生成的 pandas 数据框中转换列类型?

小智 3

SPARK-21766 ( https://issues.apache.org/jira/browse/SPARK-21766 ) 解释了您观察到的行为。

作为解决方法,您可以在 toPandas() 之前调用 fillna(0):

df1 = sc.createDataFrame([(0, None), (None, 8)], ["src_ip", "dest_ip"])
print(df1.dtypes)

# Reproduce the issue
pdf1 = df1.toPandas()
print(pdf1.dtypes)

# A workaround
pdf2 = df1.fillna(0).toPandas()
print(pdf2.dtypes)
Run Code Online (Sandbox Code Playgroud)