Python 列表转字符串
时间: 2023-11-05 20:21:43 浏览: 81
Python列表转字符串可以使用join()方法,例如:
```
my_list = ['apple', 'banana', 'orange']
my_string = ','.join(my_list)
print(my_string)
```
输出结果为:
```
apple,banana,orange
```
而将Pyspark DataFrame列从列表转换为字符串,可以使用concat_ws()函数,例如:
```
from pyspark.sql.functions import concat_ws
df = spark.createDataFrame([(1, ['apple', 'banana']), (2, ['orange', 'grape'])], ['id', 'fruits'])
df.show()
# +---+-------------+
# | id| fruits|
# +---+-------------+
# | 1|[apple, banana]|
# | 2|[orange, grape]|
# +---+-------------+
df = df.withColumn('fruits_str', concat_ws(',', 'fruits'))
df.show()
# +---+-------------+-------------+
# | id| fruits| fruits_str|
# +---+-------------+-------------+
# | 1|[apple, banana]| apple,banana|
# | 2|[orange, grape]|orange,grape |
# +---+-------------+-------------+
```
其中,concat_ws()函数的第一个参数是分隔符,第二个参数是要转换的列名。
阅读全文