Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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 2.7 如何从其他列创建列作为数组(被不兼容的类型卡住了)?_Python 2.7_Apache Spark Sql - Fatal编程技术网

Python 2.7 如何从其他列创建列作为数组(被不兼容的类型卡住了)?

Python 2.7 如何从其他列创建列作为数组(被不兼容的类型卡住了)?,python-2.7,apache-spark-sql,Python 2.7,Apache Spark Sql,假设我有一些订阅数据,如下所示: user_id subscription_id expires_at 0238423 113 12/1/18 0238423 938 11/1/18 0238423 901 10/1/18 现在,我想创建一个新列,它是订阅id的可调用数组,并在列处过期: user_id subs

假设我有一些订阅数据,如下所示:

user_id      subscription_id       expires_at
0238423            113              12/1/18
0238423            938              11/1/18
0238423            901              10/1/18
现在,我想创建一个新列,它是订阅id的可调用数组,并在列处过期:

user_id          subscription_id    expires_at         Array_Col
0238423            113              12/1/18          [113, 12/1/18]
0238423            938              11/1/18          [938, 11/1/18]
0238423            901              10/1/18          [901, 10/1/18]
问题是我无法获得正确的结构类型。我已将它们转换为字符串,但无法正确地对其进行迭代。我还希望最终收集此列上的\u集,以便为每个用户\u id生成一个数组。我的结构有什么问题

这是我的密码:

def create_struct(subscription_id, expires_at):
    x = [subscription_id, expires_at]
    return x  

create_struct = udf(create_struct, ArrayType(StructType([
    StructField("sub_id", StringType(), False),
    StructField("expiration", TimestampType(), True)])))

df = df.withColumn('expiration_dict', create_struct(df.subscription_id, df.expires_at))

我认为您需要一个结构类型的列,而不是数组类型。将两个不同类型的列放入一个数组不是一个好主意。要创建结构类型列,只需调用struct函数:

from pyspark.sql.functions import struct
df.withColumn('Struct_Col', struct(df.subscription_id, df.expires_at)).show()

#+-------+---------------+----------+--------------+
#|user_id|subscription_id|expires_at|    Struct_Col|
#+-------+---------------+----------+--------------+
#| 238423|            113|   12/1/18|[113, 12/1/18]|
#| 238423|            938|   11/1/18|[938, 11/1/18]|
#| 238423|            901|   10/1/18|[901, 10/1/18]|
#+-------+---------------+----------+--------------+

或者,如果需要列数组,请使用spark.sql.functions中的array()

df.withColumn("Array_Col", array($"subscription_id", $"expires_at"))