簡體   English   中英

如何查找pyspark數據幀的特定列是否包含數值

[英]How to find if a specific column of a pyspark dataframe contains numeric value

我正在使用 pyspark 進行數據轉換。 下面是包含一些字母數字字符的數據框。

    +------------------------------------------------+
    |Part1                                           |
    +------------------------------------------------+
    |1 HKY TBT TPP 190326 115346       5 C           |
    |51 HKK ABB TYR B    190326 000526    13 C       |
    +------------------------------------------------+

我想從列中提取第二個和第三個整數值。 下面是我需要的數據框

    +------------------------------------------------+-------------+-------------+
    |Part1                                           |     Part2   |   Part3     |
    +------------------------------------------------+-------------+-------------+
    |1 HKY TBT TPP 190326 115346       5 C           | 190326      |  115346     |
    |51 HKK ABB TYR B    190327 000526    13 C       | 190327      |  000526     |
    +------------------------------------------------+-------------+-------------+

我使用了子字符串,但數值的位置可能會改變。 你能幫忙嗎?

您可以使用regexp_extract

df = spark_session.createDataFrame([
    Row(Part1 = "1 HKY TBT TPP 190326 115346       5 C"),
    Row(Part1 = "51 HKK ABB TYR B    190326 000526    13 C")
])

regex = r'^(\d+)\s[^\d]*(\d+)\s[^\d]*(\d+)'
df.withColumn("Part2", regexp_extract(col("Part1"), regex, 2))\
    .withColumn("Part3", regexp_extract(col("Part1"), regex, 3))\
    .show()

輸出:

+--------------------+------+------+
|               Part1| Part2| Part3|
+--------------------+------+------+
|1 HKY TBT TPP 190...|190326|115346|
|51 HKK ABB TYR B ...|190326|000526|
+--------------------+------+------+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM