Pyspark 拆分行和翻转列值

Pyspark 拆分行和翻转列值,pyspark,Pyspark,如何最好地将一行转换为2,并将第二行的src_*到dest_*和dest_*到src_*的值翻转 |source_ip |destination_ip|src_port|dst_port| |192.168.0.1|10.0.0.1 |5000 |22 | 进入 您可以选择source\u ip、src\u port、dest\u port,然后将其与dest\u ip、**dst\u port\u src\u port**合并 df = spark.createD

如何最好地将一行转换为2,并将第二行的src_*到dest_*和dest_*到src_*的值翻转

|source_ip  |destination_ip|src_port|dst_port|
|192.168.0.1|10.0.0.1      |5000    |22      |
进入


您可以选择
source\u ip、src\u port、dest\u port
,然后将其与
dest\u ip、**dst\u port\u src\u port**
合并

df = spark.createDataFrame([['192.168.0.1','10.0.0.1',5000,22]],['source_ip','destination_ip','src_port','dst_port'])
df2 = df.select(['source_ip','src_port','dst_port']).union(df.select(['destination_ip','dst_port','src_port']))
df2 = df2.withColumnRenamed("source_ip", "ip")
df2.show()
输出:

+-----------+--------+--------+
|         ip|src_port|dst_port|
+-----------+--------+--------+
|192.168.0.1|    5000|      22|
|   10.0.0.1|      22|    5000|
+-----------+--------+--------+
+-----+-----------+-----------+--------+--------+
|colno|somothercol|         ip|src_port|dst_port|
+-----+-----------+-----------+--------+--------+
|    1|        xxx|192.168.0.1|    5000|      22|
|    1|        xxx|   10.0.0.1|      22|    5000|
+-----+-----------+-----------+--------+--------+
后续:当您有n列时。所有常量列都可以保存在一个变量中,而交换列可以保存在另一个变量中

df = spark.createDataFrame([['1','xxx','192.168.0.1','10.0.0.1',5000,22]],['colno','somothercol','source_ip','destination_ip','src_port','dst_port'])
constant_columns = ['colno','somothercol']
swap_columns1 = ['source_ip','src_port','dst_port']
swap_columns2 = ['destination_ip','dst_port','src_port']
df2 = df.select([*constant_columns,*swap_columns1]).union(df.select([*constant_columns,*swap_columns2]))
df2 = df2.withColumnRenamed("source_ip", "ip")
df2.show()
输出:

+-----------+--------+--------+
|         ip|src_port|dst_port|
+-----------+--------+--------+
|192.168.0.1|    5000|      22|
|   10.0.0.1|      22|    5000|
+-----------+--------+--------+
+-----+-----------+-----------+--------+--------+
|colno|somothercol|         ip|src_port|dst_port|
+-----+-----------+-----------+--------+--------+
|    1|        xxx|192.168.0.1|    5000|      22|
|    1|        xxx|   10.0.0.1|      22|    5000|
+-----+-----------+-----------+--------+--------+

好极了有没有一个简单的方法来扩展这个。假设我有大约25列,但我只需要交换其中的5列。其余部分将保留,但需要成为结果的一部分df@Chris更新了我的答案看一看。谢谢。输出不正确,因为在followuphi中没有交换,因此我得到的语法无效。我使用的是v2.4.0,您使用的是python2吗?