我需要将列表中的数据附加到特定列。 我有4个列表:
orderNumber = ['123456789']
countryOfOrigin = ['United Kingdom']
sizeList = ['2', '4']
quantityList = ['10', '12']
我还有一个带有以下标题的CSV文件:
OrderNumber COO Size QTY
我需要在这些CSV的正确列中附加这些列表。而且,如果列表中只有一项,则数据会被简单地复制以填充所有行
OrderNumber COO Size QTY
123456789 United Kingdom 2 10
123456789 United Kingdom 4 20
这是我尝试过的。但它所做的一切却将所有内容都添加到了同一列中
orderNumber = ['123456789']
countryOfOrigin = ['United Kingdom']
sizeList = ['2', '4']
quantityList = ['10', '12']
header = ["OrderNumber", "COO", "Size", "QTY"]
order = pd.DataFrame(orderNumber)
order.to_csv('C:/Users/user/Desktop/Pandas-Example2.csv', mode='a', index=False)
size = pd.DataFrame(sizeList, columns=["Size"])
size.to_csv('C:/Users/user/Desktop/Pandas-Example2.csv', mode='a', index=False)
您知道如何解决此问题吗?
答案 0 :(得分:3)
如果可能的话,改为使用一个元素仅列出标量,创建标量/列表的字典并传递给DataFrame
构造函数-所有列表的长度必须相同:
orderNumber = '123456789'
countryOfOrigin = 'United Kingdom'
sizeList = ['2', '4']
quantityList = ['10', '12']
d = {"OrderNumber": orderNumber, "COO":countryOfOrigin, "Size":sizeList, "QTY":quantityList}
order = pd.DataFrame(d)
print (order)
OrderNumber COO Size QTY
0 123456789 United Kingdom 2 10
1 123456789 United Kingdom 4 12
如果输入始终是列表,则可以使用一些预处理:
orderNumber = ['123456789']
countryOfOrigin = ['United Kingdom']
sizeList = ['2', '4']
quantityList = ['10', '12']
vals = [orderNumber, countryOfOrigin, sizeList, quantityList]
header = ["OrderNumber", "COO", "Size", "QTY"]
d = {a: b[0] if len(b) == 1 else b for a, b in zip(header, vals)}
order = pd.DataFrame(d)
print (order)
OrderNumber COO Size QTY
0 123456789 United Kingdom 2 10
1 123456789 United Kingdom 4 12