如何将isin函数与文本文件中的值一起使用? [英] How to use isin function with values from text file?

查看:97
本文介绍了如何将isin函数与文本文件中的值一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用外部文件过滤数据框.

I'd like to filter a dataframe using an external file.

这是我现在使用过滤器的方式:

This is how I use the filter now:

val Insert = Append_Ot.filter(
  col("Name2").equalTo("brazil") ||
  col("Name2").equalTo("france") ||
  col("Name2").equalTo("algeria") ||
  col("Name2").equalTo("tunisia") ||
  col("Name2").equalTo("egypte"))

我不想使用硬编码的字符串文字,而是创建一个外部文件,并使用其值作为过滤依据.

Instead of using hardcoded string literals, I'd like to create an external file with the values to filter by.

所以我创建了这个文件:

So I create this file:

val filter_numfile = sc.textFile("/user/zh/worskspace/filter_nmb.txt")
  .map(_.split(" ")(1))
  .collect

这给了我

filter_numfile: Array[String] = Array(brazil, france, algeria, tunisia, egypte)

然后,我在Name2列上使用isin函数.

And then, I use isin function on Name2 column.

val Insert = Append_Ot.where($"Name2".isin(filter_numfile: _*))

但这给了我一个空的数据框.为什么?

But this gives me an empty dataframe. Why?

推荐答案

我只是在他的答案很完美,但可能会出现大小写不匹配的情况,因此您还必须检查大小写是否不匹配

His answer is perfect but there might be some case unmatch so you will have to check for case mismatch as well

tl; dr 确保字母使用大小写一致,即它们全部为大写或小写.只需使用upperlower标准函数即可.

tl;dr Make sure that the letters use consistent case, i.e. they are all in upper or lower case. Simply use upper or lower standard functions.

让您说您输入的文件为

1 Algeria
2 tunisia
3 brazil
4 Egypt

您阅读了文本文件,并将所有国家/地区更改为小写

you read the text file and change all the countries to lowercase as

val countries = sc.textFile("path to input file").map(_.split(" ")(1).trim)
  .collect.toSeq
val array = Array(countries.map(_.toLowerCase) : _*)

然后您有了数据框

val Append_Ot = sc.parallelize(Seq(("brazil"),("tunisia"),("algeria"),("name"))).toDF("Name2")

在以下条件下应用

import org.apache.spark.sql.functions._
val Insert = Append_Ot.where(lower($"Name2").isin(array : _* ))

您应该将输出显示为

+-------+
|Name2  |
+-------+
|brazil |
|tunisia|
|algeria|
+-------+

数据框为空也可能是由于拼写不匹配.

The empty dataframe might be due to spelling mismatch too.

这篇关于如何将isin函数与文本文件中的值一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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