选择在pyspark中包含字符串的列

Man*_*que 2 python pyspark pyspark-sql

我有一个带有很多列的pyspark数据帧,我想选择包含某个字符串的字符串和其他字符串。例如:

df.columns = ['hello_world','hello_country','hello_everyone','byebye','ciao','index']
Run Code Online (Sandbox Code Playgroud)

我想选择包含'hello'的列以及名为'index'的列,因此结果将是:

['hello_world','hello_country','hello_everyone','index']
Run Code Online (Sandbox Code Playgroud)

我想要类似的东西 df.select('hello*','index')

提前致谢 :)

编辑:

我找到了快速解决问题的方法,所以我以问答形式回答自己。如果有人看到我的解决方案并可以提供更好的解决方案,我将不胜感激

nee*_*ani 6

您还可以尝试使用Spark 2.3 中引入的colRegex函数,其中您也可以将列名指定为正则表达式。


Man*_*que 5

我发现了一种快速而优雅的方法:

selected = [s for s in df.columns if 'hello' in s]+['index']
df.select(selected)
Run Code Online (Sandbox Code Playgroud)

使用此解决方案,我可以添加更多所需的列,而无需编辑Ali AzG建议的for循环。