【问题标题】:How to unstack a column to create multiple columns out of it in pyspark?如何在 pyspark 中取消堆叠列以从中创建多个列?
【发布时间】:2023-01-02 19:51:49
【问题描述】:
我有包含以下格式数据的 csv 文件
| row_num |
classes |
| 1 |
0:0.2,1:0.3,2:0.5 |
| 2 |
0:0.1,1:0.5:2:0.4 |
| 3 |
0:0.4,1:0.5:2:0.1 |
| 4 |
0:0.2,1:0.4:2:0.4 |
我希望它按如下方式转换:
| row_num |
class_0 |
class_1 |
class_2 |
| 1 |
0.2 |
0.3 |
0.5 |
| 2 |
0.1 |
0.5 |
0.4 |
| 3 |
0.4 |
0.5 |
0.1 |
| 4 |
0.2 |
0.4 |
0.4 |
请帮助我使用 pyspark 进行此转换。
【问题讨论】:
标签:
python
pyspark
transformation
【解决方案1】:
应该进行您描述的转换的 Python 代码:
import csv
# Open the input CSV file
with open('input.csv', 'r') as input_file:
# Create a CSV reader object
reader = csv.reader(input_file)
# Skip the header row
next(reader)
# Open the output CSV file
with open('output.csv', 'w', newline='') as output_file:
# Create a CSV writer object
writer = csv.writer(output_file)
# Write the header row
writer.writerow(['row_num', 'class_0', 'class_1', 'class_2'])
# Loop over the rows in the input file
for row in reader:
# Split the 'classes' field on ','
class_values = row[1].split(',')
# Convert the values to a dictionary
class_dict = {int(x.split(':')[0]): float(x.split(':')[1]) for x in class_values}
# Write the row to the output file
writer.writerow([row[0], class_dict.get(0, 0.0), class_dict.get(1, 0.0), class_dict.get(2, 0.0)])
此代码将读取输入 CSV 文件,跳过标题行,然后遍历其余行。对于每一行,它将在 ',' 上拆分类字段,将值转换为字典,然后使用 row_num 字段和字典中 class_0、class_1 和 class_1 下的值将新行写入输出 CSV 文件class_2 列。