Python 如何使用jupyter转换csv文件?

Python 如何使用jupyter转换csv文件?,python,csv,jupyter,transpose,Python,Csv,Jupyter,Transpose,免责声明,我是一名编码初学者,因此请轻松操作,提前感谢 在使用jupyter中的python将数据保存到csv文件之前,如何将数据转换为 这是我的密码: import csv Col1 = "Product Name" Col2 = "Product Image Is Thumbnail - 1" Col3 = "Product Code/SKU" Col4 = "Product Description" Col5 = "Price" Col6 = "Cost Price" Col7 = "P

免责声明,我是一名编码初学者,因此请轻松操作,提前感谢

在使用jupyter中的python将数据保存到csv文件之前,如何将数据转换为

这是我的密码:

import csv

Col1 = "Product Name"
Col2 = "Product Image Is Thumbnail - 1"
Col3 = "Product Code/SKU"
Col4 = "Product Description"
Col5 = "Price"
Col6 = "Cost Price"
Col7 = "Product Image File - 1"
Col8 = "Product Image File - 2"


mydictionary={Col1:[], Col2:[], Col3:[], Col4 :[], Col5:[], Col6:[],  Col7:[], Col8:[]}
csvFile = csv.reader(open("wedding.csv"))
for row in csvFile:
  mydictionary[Col1].append(row[2])
  mydictionary[Col2].append(row[6])
  mydictionary[Col3].append(row[4])
  mydictionary[Col4].append(row[11]) 
  mydictionary[Col5].append(row[7])
  mydictionary[Col6].append(row[8])
  mydictionary[Col7].append(row[9])
  mydictionary[Col8].append(row[10])


print (mydictionary)

with open('test.csv', 'w') as csv_file1:
    writer = csv.writer(csv_file1, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for key, value in mydictionary.items():
       writer.writerow([key, value])``

您正在错误地构建数据对象。CSV是数据行,所以最好的选择是创建一个行数组,然后将其写出。大概是这样的:

import csv

# First row is the title row
rows = [(
    "Product Name",
    "Product Image Is Thumbnail - 1",
    "Product Code/SKU",
    "Product Description",
    "Price",
    "Cost Price",
    "Product Image File - 1",
    "Product Image File - 2"
)]

csvFile = csv.reader(open("wedding.csv"))
for row in csvFile:
    # add a row of data transposing positions as desired
    # NOTE: the double parenthesis are intentional, we're appending a tuple to the array  
    rows.append((row[2], row[6], row[4], row[11], row[7], row[8], row[9], row[10]))

print(rows)

with open('test.csv', 'w') as csv_file1:
    writer = csv.writer(csv_file1, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for row in rows:
        # write out each row
        writer.writerow(row)

如果将数据加载到2d
numpy
数组中,
transpose
将非常简单
zip
是一种方便的方法,可以对列表执行类似的操作,例如
list(zip([1,2,3],[4,5,6])
。如果没有一个压缩包,人们可能不会使用您的代码并提出改进建议。这段代码是按原样运行,还是有错误?或者错误的结果。这个“转置”应该放在哪里?