我有基于Excel的数据集需要转换。我会在学习Python时请求基于Python的解决方案,然后可以读取/修改代码。我可以使用基于Excel或CSV的输入/输出。
这就是我的数据
频道 条件 值1 值2 值3 (标头)< / em>的
A频道A条件B直播飞行员
频道A条件B直播直播
B频道条件C试点飞行员飞行员
频道C条件D现场直播
这是我想要的输出:
频道 条件 价值(全部) 状态 (标题。如果这样做,我很好不显示在输出上)
频道A条件B值1直播
频道A条件B值2直播
渠道A条件B值3飞行员
频道A条件B值1直播
渠道A条件B值2飞行员
频道A条件B值3直播......
基本上,它是每个“值”的频道和条件的重复,应该从列标题和它自己的数据集(Live / Pilot)获取。
我很感激一些帮助,因为我有大约1000行这样的转换
这是一张代表我想要的图像
编辑2:屏幕截图上有一个类型。最后3行应该读取通道B,而不是通道A.
答案 0 :(得分:0)
这样的事情应该适用于这项工作。
import csv
transformed = []
with open('excel.csv', newline='') as csvfile:
r = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in r:
channel, condition, *vals = row
for val in vals:
transformed.append([channel, condition, val])
with open('transformed.csv', 'w', newline='') as csvfile:
w = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row in transformed:
w.writerow(' '.join(row))
答案 1 :(得分:0)
尝试使用xlrd模块。类似的东西:
import xlrd
wb = xlrd.open_workbook(path)
sheet = wb.sheet_by_index(index)
column_list = range(0, sheet.ncols)
val_name = [sheet.cell_value(rowx=0, colx=i) for i in column_list]
channel = val_name.pop(0)
condition = val_name.pop(0)
print(channel, condition, "Value *", "Status")
lines = []
for r in range(1, sheet.nrows):
row = [sheet.cell_value(rowx=r, colx=i) for i in column_list]
channel = row[0]
condition = row[1]
values = row[2:]
lines = zip( [channel]*len(values),
[condition]*len(values),
val_name,
values)
for l in lines:
print(l)