pyspark报错 TypeError: sample() got an unexpected keyword argument ‘n‘
程序员文章站
2022-06-13 10:01:51
...
使用pyspark连接数据库获取相应符合条件的数据,然后随机抽样。
import pandas as pd
df1 = spark.sql('''
SELECT spe_id,item_num,item_bare_price,0 as label
FROM rm_erp_purchase_in_stock_item_source
where group_id in (1001)
and order_in_stock_time between '2020-01-01' and '2020-06-30'
and item_bare_price>=lower_6 and item_bare_price<=upper
''')
df2 = df1.sample(n=100,replace=True)#有放回抽取100行
原本以为df1得出来的是dataframe类型,可以直接使用pandas包中的sample方法。但是运行报错:TypeError: sample() got an unexpected keyword argument 'n'
原因:df1类型不符合sample方法中的类型
- 先看pandas包中sample的用法,自己先创建一个pandas包中的例子:
sq = pd.DataFrame({'coll':[9,8,7,6],'weight_column':[0.5,0.4,0.1,0]})
temp = sq.sample(n=2,replace=True)
type(temp)
输出:<class 'pandas.core.frame.DataFrame'>
type(df1)
输出:<class 'pyspark.sql.dataframe.DataFrame'>
很明显,两者类型是不一样的。
解决办法: 将spark.DataFrame 转换成 pandas.DataFrame"
df1.toPandas()
完美解决!
拓展:将pandas.DataFrame 转换成 spark.DataFrame
from pyspark import SparkContext
sc = SparkContext()
sqlContext = SQLContext(sc)
spark_df = sqlContext.createDataFrame(sq)
推荐阅读
-
报错解决Python Error fix-TypeError: _mean() got an unexpected keyword argument ‘dim‘
-
TypeError: softmax() got an unexpected keyword argument 'axis' 解决办法
-
Django报错:TypeError: render() got an unexpected keyword argument 'renderer'
-
TypeError: login() got an unexpected keyword argument 'template_name'
-
TypeError: filter() got an unexpected keyword argument
-
解决 报错 TypeError: interleave() got an unexpected keyword argument ‘deterministic‘
-
TypeError: __init__() got an unexpected keyword argument 'shape'
-
Django TypeError: render() got an unexpected keyword argument 'renderer'
-
TypeError: got an unexpected keyword argument ‘id‘
-
pyspark报错 TypeError: sample() got an unexpected keyword argument ‘n‘