使用pyspark获取列的数据类型 [英] get datatype of column using pyspark

查看:994
本文介绍了使用pyspark获取列的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We are reading data from MongoDB Collection. Collection column has two different values (e.g.: (bson.Int64,int) (int,float) ).

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

I am trying to get a datatype using pyspark.

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

My problem is some columns have different datatype.

假设quantityweight是列

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

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

Actually we didn't defined data type for any column of mongo collection.

当我从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数据帧输出的示例:

Example output in jupyter notebook for a spark dataframe with 4 columns:

count_column_types(my_spark_df)

这篇关于使用pyspark获取列的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆