在 Pyspark 中创建一个新列,该列在另一个可用列上计算

时间:2021-07-19 09:31:17

标签: python pyspark

我有一个如下的数据框:

>>> df
   Name    id
0   Tom   103
1  Jack   109
2  nick  9518
3  juli  1890

我想创建一个列作为 super_id 即 i) 如果 id 是 3 位,那么 super_id 是零加上第一个整数 ii) 如果 id 是 4 位那么 super id 是前两个整数.

>>> df
   Name    id super_id
0   Tom   103       01
1  Jack   109       01
2  nick  9518       95
3  juli  1890       18

我有以下相同的 python 代码,但不知道如何将其转换为 pyspark 代码。

import pandas as pd

# initialise data of lists.
data = {'Name':['Tom', 'Jack', 'nick', 'juli'],
        'id':[103, 109, 9518, 1890]}
 
# Creates pandas DataFrame.
df = pd.DataFrame(data)

#Create super id
df['super_id'] = df.id.astype('int').astype('str').str.zfill(4).str[0:2]

在pyspark中尝试出错

df= df.withColumn('super_id', df['id'].astype('int').astype('str').str.zfill(4).str[0:2])

1 个答案:

答案 0 :(得分:1)

您需要使用 spark functions 来做到这一点:

 import cv2

 
 class try():
     def __init__(self, ....):


         if Count>= 1 and Count <= 5:
             cv2.putText(frame, "Yuppi", (10, 800), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 4)
             print("Yuppi, {}".format(Count))
             Count +=1
        
         if Count>= 6 and Count <= 10:
             cv2.putText(frame, "Yuppi1", (10, 800), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 4)
             print("Yuppi1, {}".format(Count))
             Count +=1