![]() |
刚毅的企鹅 · Web API(三):创建Web ...· 1 年前 · |
![]() |
无聊的葡萄酒 · Spring Security -- ...· 1 年前 · |
![]() |
含蓄的钢笔 · Java——实现json ...· 1 年前 · |
![]() |
玩滑板的柚子 · POW(C/C++中的数学函数)_百度百科· 2 年前 · |
我在pyspark有数据帧。它的一些数字列包含'nan‘,所以当我读取数据并检查dataframe的模式时,这些列将具有'string’类型。如何将它们更改为int类型。我将'nan‘值替换为0,并再次检查了架构,但同时也显示了这些列的字符串类型。我遵循以下代码:
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()
我的数据如下所示:
在这里,包含整数值的“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
![]() |
无聊的葡萄酒 · Spring Security -- FilterInvocationSecurityMetadataSource 与 AccessDecisionManager - 爱吃西瓜的番茄酱 - 博客园 1 年前 |
![]() |
玩滑板的柚子 · POW(C/C++中的数学函数)_百度百科 2 年前 |