根据值

时间:2015-08-20 13:47:14

标签: php python csv

我有这个CSV

idSensor,ReadData
1010,1459
1010,1477
1011,1307
1011,1183
1012,1050
1012,1015
1013,575
1013,474

我想将此CSV转换为:

1010,1011,1012,1013
1459,1307,1050,575
1477,1183,1015,474

你能帮助我用python或PHP语言转换我的CSV吗?

1 个答案:

答案 0 :(得分:0)

Python 2和Python 3的解决方案。

使用OrderedDict按行第一列中的值对行进行分组,然后使用字典键和值的一些聪明zipping来生成所需的格式:

data = [s.split(',') for s in '''1010,1459
          1010,1477
          1011,1307
          1011,1183
          1012,1050
          1012,1015
          1013,575
          1013,474'''.split()]

from collections import OrderedDict
d = OrderedDict()
for key, value in data:
    d[key] = d.get(key, []) + [value]

grouped_data = [row for row in zip(*[[k]+v for k,v in d.items()])]
for row in grouped_data:
    print(','.join(row))

<强>输出

1010,1011,1012,1013
1459,1307,1050,575
1477,1183,1015,474
相关问题