我们正在从MongoDB Collection读取数据。 Collection列具有两个不同的值(例如(bson.Int64,int) (int,float))。

我正在尝试使用pyspark获取数据类型。

我的问题是某些列具有不同的数据类型。

假设quantityweight是列

quantity           weight
---------          --------
12300              656
123566000000       789.6767
1238               56.22
345                23
345566677777789    21

实际上,我们没有为mongo集合的任何列定义数据类型。

当我从pyspark dataframe查询计数时
dataframe.count()

我有这样的异常
"Cannot cast STRING into a DoubleType (value: BsonString{value='200.0'})"

最佳答案

import pandas as pd
pd.set_option('max_colwidth', -1) # to prevent truncating of columns in jupyter

def count_column_types(spark_df):
    """Count number of columns per type"""
    return pd.DataFrame(spark_df.dtypes).groupby(1, as_index=False)[0].agg({'count':'count', 'names': lambda x: " | ".join(set(x))}).rename(columns={1:"type"})

在jupyter笔记本中为4列的spark数据帧输出的示例:

count_column_types(my_spark_df)

apache-spark - 使用pyspark获取列的数据类型-LMLPHP

关于apache-spark - 使用pyspark获取列的数据类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45033315/

10-12 21:44
查看更多