我在 pyspark 中有数据框。它的一些数字列包含 nan
,因此当我读取数据并检查数据框的架构时,这些列将具有 string
类型。
我如何将它们更改为 int 类型。我用 0 替换了 nan
值并再次检查了架构,但它也显示了这些列的字符串类型。我遵循以下代码:
data_df = sqlContext.read.format("csv").load('data.csv',header=True, inferSchema="true")
data_df.printSchema()
data_df = data_df.fillna(0)
data_df.printSchema()
https://i.stack.imgur.com/JslnA.png
这里的列 Plays
和 drafts
包含整数值,但由于这些列中存在 nan
,它们被视为字符串类型。
from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))
您可以为每一列运行循环,但这是将字符串列转换为整数的最简单方法。
将 NaN
替换为 0
后,您可以使用 cast
(as int),
data_df = df.withColumn("Plays", df.call_time.cast('float'))
如果您有多个需要修改的字段,另一种方法是使用 StructField。
前任:
from pyspark.sql.types import StructField,IntegerType, StructType,StringType
newDF=[StructField('CLICK_FLG',IntegerType(),True),
StructField('OPEN_FLG',IntegerType(),True),
StructField('I1_GNDR_CODE',StringType(),True),
StructField('TRW_INCOME_CD_V4',StringType(),True),
StructField('ASIAN_CD',IntegerType(),True),
StructField('I1_INDIV_HHLD_STATUS_CODE',IntegerType(),True)
]
finalStruct=StructType(fields=newDF)
df=spark.read.csv('ctor.csv',schema=finalStruct)
输出:
前
root
|-- CLICK_FLG: string (nullable = true)
|-- OPEN_FLG: string (nullable = true)
|-- I1_GNDR_CODE: string (nullable = true)
|-- TRW_INCOME_CD_V4: string (nullable = true)
|-- ASIAN_CD: integer (nullable = true)
|-- I1_INDIV_HHLD_STATUS_CODE: string (nullable = true)
后:
root
|-- CLICK_FLG: integer (nullable = true)
|-- OPEN_FLG: integer (nullable = true)
|-- I1_GNDR_CODE: string (nullable = true)
|-- TRW_INCOME_CD_V4: string (nullable = true)
|-- ASIAN_CD: integer (nullable = true)
|-- I1_INDIV_HHLD_STATUS_CODE: integer (nullable = true)
这是一个稍微长的过程来 cast ,但优点是可以完成所有必需的字段。
需要注意的是,如果只为必需的字段分配了数据类型,那么生成的数据帧将只包含那些被更改的字段。
不定期副业成功案例分享