我有一個包含以下列的 excel(.xlsx) 檔案
Location Month Desc Position Budget
EUR 1/1/2020 In Europe Right 34%
AUS 1/1/2020 In Australia Left >22%
在 pandas df 中閱讀此檔案時,我在 Budget col 中遇到問題。收到以下錯誤:
field Budget: Can not merge type <class 'pyspark.sql.types.DoubleType'> and <class 'pyspark.sql.types.StringType'>
Could not convert '>22%' with type str: tried to convert to double
我正在嘗試使用此代碼:
from pyspark.sql import SparkSession
import pandas
spark = SparkSession.builder.appName("Test").getOrCreate()
pdf = pandas.read_excel(parent_path 'file1.xlsx', sheet_name='Sheet1')
fileSchema = StructType([
StructField("Location", StringType()),
StructField("Month", DateType()),
StructField("Desc", StringType()),
StructField("Position", StringType()),
StructField("Budget", StringType())])
pdf.fillna('')
df = spark.createDataFrame(pdf)
df.show()
我需要閱讀多個excel檔案。如何在這里處理資料型別問題?任何建議
uj5u.com熱心網友回復:
看起來你可以使用自定義來處理這個問題converter:
def bcvt(x):
return float(x.replace('>','').replace('%',''))/100
dfd = pd.read_csv(r'd:\jchtempnew\t1.csv', converters={'Budget': bcvt})
dfd
Location Month Desc Position Budget
0 EUR 1/1/2020 In Europe Right 0.34
1 AUS 1/1/2020 In Australia Left 0.22
(根據@user128029推薦更新)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/432900.html
上一篇:帶字典的交叉資料框
