我需要帮助我的数据准备一个项目,我正在工作。我有2列csv文件,一个包含订单号,第二个包含购买的项目。
以下是我所拥有的示例:
1 A
1 B
1 C
2 A 
2 D 
3 F
3 G
3 K我需要将其转换为:
1 A B C
2 A D
3 F G K)这只是我做的一个样品。我有70k行)任何帮助都将是惊人的。SQL / Python / excel是我知道如何使用的工具。因此,如果可能的话,其中之一的答案将是最好的。谢谢!
发布于 2020-02-18 22:19:13
您可以使用ROW_NUMBER () OVER (PARTITION BY NUMBER ORDER BY LETTER) (内部查询),然后使用子查询可以选择字母作为列。
发布于 2020-02-18 22:22:38
使用Python和collections.defaultdict,这非常简单。
import collections
order_to_products = collections.defaultdict(list)
with open('input.csv') as inp:
   for l in inp:
      order_id, *products = l.split()
      order_to_products[order_id].extend(products)
for order_id, products in order_to_products.items():
   print(order_id, ' '.join(products))(作为额外的好处,这实际上支持具有多个产品的输入行。)
例如。
$ cat > input.csv
1 A
1 B
1 C
2 A
2 D
3 F
3 G
3 K
$ python3
>>> import collections
>>> order_to_products = collections.defaultdict(list)
>>> with open('input.csv') as inp:
...    for l in inp:
...       order_id, *products = l.split()
...       order_to_products[order_id].extend(products)
...
>>> for order_id, products in order_to_products.items():
...    print(order_id, ' '.join(products))
...
1 A B C
2 A D
3 F G Khttps://stackoverflow.com/questions/60282903
复制相似问题