我有基于Excel的数据集,需要转换。当我学习Python时,我会请求一个基于Python的解决方案,然后可以读取/修改代码。我对基于Excel或CSV的输入/输出都没有意见。
这是我的数据看起来像
通道条件 Value1 Value2 Value3 3E 211
(报头)
A频道B状态现场直播飞行员
A频道B状态现场直播
B通道条件C飞行员引航员
C频道条件D现场直播
,这是我想要的输出:
通道条件值(All) Status (报头)如果这没有出现在输出中,我就可以了)
A频道B状态Value1实况
A频道B状态Value2实况
通道A条件B值3导频
通道A条件B值1活
通道A条件B值2导频
A频道条件B值3活..。
基本上,它是对每个“值”的通道和条件的重复,这些值应该从列标题和它自己的数据集(Live/Pilot)中获取。
我希望得到一些帮助,因为我有大约1000行这样的转换要做。
这是一个代表我想要的图像
编辑2:截图上有一种类型。最后3行应为B频道,而不是A频道。
发布于 2013-12-17 15:31:19
尝试使用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)
发布于 2013-12-17 15:30:27
像这样的事情应该适合工作。
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))
https://stackoverflow.com/questions/20646640
复制相似问题