我需要帮助在python中构建一个脚本来转置csv的一部分,如下例所示:
[[0A,0B,0C,0D,0E,0F]
[01,02,03,04,05,06]
[07,08,09,10,11,12]
[13,14,15,16,17,18]
[19,20,21,22,23,24]]
它:
[[0A, 0B, 0C]
[01,02,03]
[01,02,04]
[01,02,05]
[01,02,06]
[07,08,09]
[07.08, 10]
[07,08,11]
.
.
.
[19,20,24]]
有没有人用python做过这种csv / xls的转换?
答案 0 :(得分:0)
[row[:3] for row in my_table]
将只提供前3列
或者我想你可以把它转移到列中获得前3个,然后将其转置回来
transposed_table = zip(*my_table)
my_cols = transposed_table[:3]
transposed_back_to_rows = zip(*my_cols)
或者如果你真的想要它在一行
zip(*list(zip(*my_table))[:3])
答案 1 :(得分:0)
如果你可以使用numpy
库,你可以使用切片来轻松实现这一目标 -
示例 -
import numpy as np
n = np.array([['0A','0B','0C','0D','0E','0F'],
['01','02','03','04','05','06'],
['07','08','09','10','11','12'],
['13','14','15','16','17','18'],
['19','20','21','22','23','24']])
print('n - ' + str(n))
n1 = np.append(n[:,:3],n[:,3:], axis = 0)
print('n1 - ' + str(n1))
输出 -
n - [['0A' '0B' '0C' '0D' '0E' '0F']
['01' '02' '03' '04' '05' '06']
['07' '08' '09' '10' '11' '12']
['13' '14' '15' '16' '17' '18']
['19' '20' '21' '22' '23' '24']]
n1 - [['0A' '0B' '0C']
['01' '02' '03']
['07' '08' '09']
['13' '14' '15']
['19' '20' '21']
['0D' '0E' '0F']
['04' '05' '06']
['10' '11' '12']
['16' '17' '18']
['22' '23' '24']]
答案 2 :(得分:0)
您可以结合使用列表切片,嵌套列表推导和itertools.chain
:
M = [['0A','0B','0C','0D','0E','0F'],
['01','02','03','04','05','06'],
['07','08','09','10','11','12'],
['13','14','15','16','17','18'],
['19','20','21','22','23','24']]
from itertools import chain
result = [M[0][:3]] + list(chain(*[[x[:2] + [y] for y in x[2:]] for x in M[1:]]))
之后,result
[['0A', '0B', '0C'],
['01', '02', '03'],
['01', '02', '04'],
['01', '02', '05'],
...
['19', '20', '23'],
['19', '20', '24']]