简体   繁体   English

在本地使用 spark/scala 查询数据帧时,如何更改列中值的输出?

[英]When querying a dataframe using spark/scala locally, how to change output of values in a column?

Im using spark/scala locally to transform json files into a dataframe .在本地使用spark/scalajson文件转换为数据帧

My current dataframe has a column with 'Male' and 'Female' values, shown below.我当前的数据框有一列包含“男性”和“女性”值,如下所示。 I want to change where you see 'Male' in the dataframe to 'M' and likewise for 'Female' to 'F' using spark -sql .我想使用 spark -sql将您在数据框中看到“男性”的位置更改为“M” ,同样将“女性”更改为“F”

So far I have:到目前为止,我有:

val results = spark.sql("SELECT name, case WHEN gender = 'Male' then 'M' WHEN gender = 'Female' then 'F' else 'Unknown' END from ocupation_table)

but it's creating a separate column and I want it to rename the values in the existing 'gender' column.但它正在创建一个单独的列,我希望它重命名现有“性别”列中的值。

Tab to view dataframe标签查看数据框

You can use Spark's withColumn(...) method to achieve this.您可以使用 Spark 的withColumn(...)方法来实现这一点。 It will replace a named column if it already exists.如果已存在,它将替换命名列。 Something like this should do the trick:像这样的事情应该可以解决问题:

import org.apache.spark.sql.functions

val results = df.withColumn("gender", substring(df("gender"), 0, 1))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用带有 scala 的 Spark dataframe 中的 JSON 类型的列获取所有值,而不考虑键 - Fetch all values irrespective of keys from a column of JSON type in a Spark dataframe using Spark with scala 将 dataframe 列的数组展平为单独的列和 Spark scala 中的相应值 - Flattening the array of a dataframe column into separate columns and corresponding values in Spark scala 数据帧列scala中的火花流JSON值 - spark streaming JSON value in dataframe column scala 如何更改数组中的 Spark Dataframe 列数据类型 - How to change Spark Dataframe column data type in an array 使用 spark/scala 将 JSON 文件加入数据帧 - Joining JSON files into a dataframe using spark/scala 使用 spark/scala 按照 json 文件中首先列出的列的顺序将 json 转换为数据帧 - Convert json to dataframe in order of which column listed first in json file using spark/scala 使用 Spark 解析 Spark 数据框中的 JSON 列 - Parse a JSON column in a spark dataframe using Spark Scala Spark - 从简单的数据帧创建嵌套的json输出 - Scala Spark - creating nested json output from simple dataframe Scala - Spark - 如何将包含一个字符串列的数据帧转换为具有rigth类型的列的DF? - Scala - Spark - How to transform a dataframe containing one string column to a DF with columns with the rigth type? Spark scala - 从数据帧列解析 json 并返回带有列的 RDD - Spark scala - parse json from dataframe column and return RDD with columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM