使用pyspark获取列的数据类型 [英] get datatype of column using pyspark
本文介绍了使用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.
假设 quantity
和 weight
是列
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 notebook 中 4 列 spark 数据帧的示例输出:
Example output in jupyter notebook for a spark dataframe with 4 columns:
count_column_types(my_spark_df)
这篇关于使用pyspark获取列的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文