Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在PySpark数据框中添加变量/条件列_Python_Apache Spark_Pyspark - Fatal编程技术网

Python 如何在PySpark数据框中添加变量/条件列

Python 如何在PySpark数据框中添加变量/条件列,python,apache-spark,pyspark,Python,Apache Spark,Pyspark,我有一个数据框,看起来像这样: Filename Type file1.A.txt file2.A.txt file3.B.txt file4.A.txt file5.B.txt ... 我想添加另一列,键入,这将取决于文件名。如果文件名中有A,则添加A;如果文件名中有AB,则添加B 我在中看到过类似的东西,但我不知道如何将其应用到我的案例中 我可以通过df=df.withColumn('NewCol',lit('a'))向Spark添加常量,但如何使用正则表达式在某些情况

我有一个数据框,看起来像这样:

Filename        Type
file1.A.txt 
file2.A.txt 
file3.B.txt 
file4.A.txt
file5.B.txt
...
我想添加另一列,
键入
,这将取决于文件名。如果文件名中有A,则添加
A
;如果文件名中有A
B
,则添加
B

我在中看到过类似的东西,但我不知道如何将其应用到我的案例中

我可以通过
df=df.withColumn('NewCol',lit('a'))
向Spark添加常量,但如何使用正则表达式在某些情况下添加某个字符串,在其他情况下添加另一个字符串


这与相关问题类似,但迈克尔·韦斯特的答案更容易输入,并且更具体。然而,我认为它仍然可以解决这个问题(尽管阅读起来会更困难)。

类似的东西应该会奏效

from pyspark.sql.functions import regexp_extract

df = spark.createDataFrame([
    ("file1.A.txt",),
    ("file2.A.txt",),
    ("file3.B.txt",),
    ("file4.A.txt",),
    ("file5.B.txt",)
  ],
  ["filenames"]
)

df.withColumn('A_or_B', regexp_extract('filenames', '^\w+\.(.*)\.txt$', 1)).show()

+-----------+------+
|  filenames|A_or_B|
+-----------+------+
|file1.A.txt|     A|
|file2.A.txt|     A|
|file3.B.txt|     B|
|file4.A.txt|     A|
|file5.B.txt|     B|
+-----------+------+

备选答案,不太笼统。 基于将文件名拆分为数组。分隔符

from pyspark.sql.functions import split, col

df = spark.createDataFrame([
    ("file1.A.txt",),
    ("file2.A.txt",),
    ("file3.B.txt",),
    ("file4.A.txt",),
    ("file5.B.txt",)
  ],
  ["filenames"]
)

df.withColumn('a_or_b', split(col("filenames"), "\.")[1]).show()

+-----------+------+
|  filenames|a_or_b|
+-----------+------+
|file1.A.txt|     A|
|file2.A.txt|     A|
|file3.B.txt|     B|
|file4.A.txt|     A|
|file5.B.txt|     B|
+-----------+------+

查看链接的副本,但您基本上需要类似
df=df.withColumn(“NewCol”),when(col(“Filename”)。类似(“%A%”),lit('A')。when(col(“Filename”)。类似(“%B%”),lit('B'))
非常感谢您的回答@pault我正在慢慢学习Spark。我接受了迈克尔·韦斯特的答案,因为它更简短,更清楚地说明了我的狭窄范围,但当/like也很有趣时,我会仔细研究,以便更好地学习它!