[英]How to convert floats to IntegerType using StructType in PySpark?
我正在嘗試從 Pandas 數據幀創建 Spark 數據幀,其中我使用 StructType class 指定列數據類型。 我已將 pandas 數據幀保存為 df,將 spark 數據幀保存為數據。
在我開始之前,csv 文件中的某處有一個錯誤,我使用了 pandas 的 read_csv 方法的參數 error_bad_lines。 我不熟悉火花等效物。
df = pd.read_csv('Amazon_Responded_Oct05.csv',error_bad_lines=False)
df.head()
>>>>
user_id_str user_followers_count text_
0 143515471.0 1503 @AmazonHelp Can you please DM me? A product I ...
1 85741735.0 149569 @SeanEPanjab I'm sorry, we're unable to DM you...
2 143515471.0 1503 @AmazonHelp It was purchased on...
3 143515471.0 1503 @AmazonHelp I am following you now, if it help...
4 85741735.0 149569 @SeanEPanjab Please give us a call/chat so we ...
注意 user_id_str 列是如何填充浮點值的,即 143515471.0 下面是引發錯誤的地方。
data_schema = [StructField('user_followers_count',IntegerType(),True),
StructField('user_id_str',StringType(),True),
StructField('text',StringType(),True)]
final_struc = StructType(fields=data_schema)
data = spark.createDataFrame(df,schema=final_struc)
>>>>
TypeError: field user_followers_count: IntegerType can not accept object 143515471.0 in type <class 'float'>
我試圖從 pandas 端解決這個問題,但沒有成功
df.astype({'user_id_str': 'int','user_followers_count':'int','text_':'str'}).dtypes
df.head(1)
>>>>
user_id_str user_followers_count text_
0 143515471.0 1503 @AmazonHelp Can you please DM me? A product I ...
總之,我采取了各種方法來實現我的目標,創建了一個包含列數據類型、IntegerType、IntegerType、StringType 的 Spark 數據框,但均未成功。 我非常感謝一種強制這種數據轉換的方法。
編輯:
最后,我嘗試過從 Spark 開始; 但這也是徒勞的。
data_1 = spark.read.csv('Amazon_Responded_Oct05.csv',schema=final_struc,enforceSchema=True)
data_1.head(5)
>>>>
+--------------------+-----------+----+
|user_followers_count|user_id_str|text|
+--------------------+-----------+----+
| null| null|null|
| null| null|null|
| null| null|null|
| null| null|null|
| null| null|null|
+--------------------+-----------+----+
only showing top 5 rows
從 pandas dataframe 轉換為 pyspark Z6A8064B5DF479455500553C47DZ5,
from pyspark.sql import Row
import pandas as pd
from pyspark.sql.types import StructField, StructType, StringType, IntegerType
#create a sample pandas dataframe
data = {'a':['hello', 'hi', 'world'], 'b':[5.0, 6.4, 9.7], 'c':[1,2,3]}
df = pd.DataFrame(data)
'''
a b c
0 hello 5.0 1
1 hi 6.4 2
2 world 9.7 3
'''
#convert second column type to integer
df = df.astype({'b':'int'})
df
'''
a b c
0 hello 5 1
1 hi 6 2
2 world 9 3
'''
#prepare the schema
fields = [StructField('a',StringType(),True),\
StructField('b',IntegerType(),True),\
StructField('c',IntegerType(),True)]
schema = StructType(fields)
#convert to a pyspark dataframe
rows = [Row(**_) for _ in df.to_dict(orient='records')]
#[Row(a='hello', b=5, c=1), Row(a='hi', b=6, c=2), Row(a='world', b=9, c=3)]
df_sp = spark.createDataFrame(rows, schema)
df_sp.show()
# +-----+---+---+
# | a| b| c|
# +-----+---+---+
# |hello| 5| 1|
# | hi| 6| 2|
# |world| 9| 3|
# +-----+---+---+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.