在Spark中获取DataFrame列的值 [英] Getting the value of a DataFrame column in Spark

查看:356
本文介绍了在Spark中获取DataFrame列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检索DataFrame列的值并将其存储在变量中.我尝试了这个:

I am trying to retrieve the value of a DataFrame column and store it in a variable. I tried this :

val name=df.select("name")
 val name1=name.collect()

但是以上都不返回名称"列的值.

But none of the above is returning the value of column "name".

火花版本:2.2.0Scala版本:2.11.11

Spark version :2.2.0 Scala version :2.11.11

推荐答案

这里有几件事.如果您想查看所有收集的数据,那就是要走的路.但是,如果您的数据太大,则会导致驱动器发生故障.

There are couple of things here. If you want see all the data collect is the way to go. However in case your data is too huge it will cause drive to fail.

因此,替代方法是检查数据框中的少量项目.我通常要做的是

So the alternate is to check few items from the dataframe. What I generally do is

df.limit(10).select("name").as[String].collect()

这将提供10个元素的输出.但是现在输出看起来不好

This will provide output of 10 element. But now the output doesn't look good

所以,第二种选择是

df.select("name").show(10)

这将打印第一个10元素,有时如果列值较大,通常会在显示"..."而不是烦人的实际值.

This will print first 10 element, Sometime if the column values are big it generally put "..." instead of actual value which is annoying.

因此有第三种选择

df.select("name").take(10).foreach(println)

使用10个元素并打印它们.

Takes 10 element and print them.

现在,在所有情况下,您都不会获得公平的数据样本,因为将选择前10个数据.因此,要真正从数据框中随机拾取,您可以使用

Now in all the cases you won't get a fair sample of the data, as the first 10 data will be picked. So to truely pickup randomly from the dataframe you can use

df.select("name").sample(.2, true).show(10)
or
df.select("name").sample(.2, true).take(10).foreach(println)

您可以检查数据框上的样本"功能

You can check the "sample" function on dataframe

这篇关于在Spark中获取DataFrame列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆