如何在pyspark数据框中将字符串类型的列转换为int形式?

neh*_*eha 20 python dataframe pyspark

我在pyspark中有数据框.它的一些数字列包含'nan',因此当我读取数据并检查数据帧的模式时,这些列将具有"字符串"类型.我怎样才能改变他们为int type.I取代了"南"值是0,并再次检查的模式,但后来又它显示是跟着下面的代码对那些columns.I字符串类型:

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()
Run Code Online (Sandbox Code Playgroud)

我的数据看起来像这样: 在此输入图像描述

这里列'Plays'和'drafts'包含整数值,但由于这些列中存在nan,它们被视为字符串类型.

Sah*_*sai 48

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()))
Run Code Online (Sandbox Code Playgroud)

您可以为每列运行循环,但这是将字符串列转换为整数的最简单方法.

  • 嗨@sahil-desai,它给了我空值。但是,虽然打印模式给了我 Integer。你能解释一下为什么吗? (4认同)

Ani*_*non 16

你可以使用cast更换后(如INT)NaN0

data_df = df.withColumn("Plays", df.call_time.cast('float'))
Run Code Online (Sandbox Code Playgroud)


Kes*_*ath 5

如果您有多个需要修改的字段,另一种方法是使用 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)
Run Code Online (Sandbox Code Playgroud)

输出:

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)
Run Code Online (Sandbox Code Playgroud)

后:

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)
Run Code Online (Sandbox Code Playgroud)

这对 cast 来说是一个稍微长的过程,但优点是可以完成所有必需的字段。

需要注意的是,如果只有必需的字段被分配了数据类型,那么结果数据帧将只包含那些被更改的字段。