简体   繁体   English

使用熊猫to_csv函数

[英]Using Pandas to_csv function

I have been experimenting with pandas, and while I have figured out how to use it to read data, I have stumbled upon some trouble in writing my output, and need your help! 我一直在尝试熊猫,虽然我想出了如何使用它来读取数据,但偶然发现在编写输出时遇到了一些麻烦,需要您的帮助!

This is my simplified code: 这是我的简化代码:

import pandas as pd

df = pd.DataFrame("prices", "product1", "product2", "product3")
prices = df.prices
product1 = df.product1
product2 = df.product2
product3 = df.product3

prices = ["Price Option 1", "Price Option 2", "Price Option 3"]
product1 = [1,2,3]
product2 = [4,5,6]
product3 = [7,8,9]

df.to_csv("output.csv") 

The expected output was supposed to be something like: 预期的输出应该是这样的:

prices    product1    product2    product3
price1       1           2           3
price2       4           5           6
price3       7           8           9

But instead I get this error: 但是相反我得到了这个错误:

Traceback (most recent call last):
  File "output.py", line 3, in <module>
    df = pd.DataFrame("prices", "product1", "product2", "product3")
  File "C:\Python27\lib\site-packages\pandas-0.14.1-py2.7-win32.egg\pandas\core\frame.py", line 194,
 in __init__
    dtype = self._validate_dtype(dtype)
  File "C:\Python27\lib\site-packages\pandas-0.14.1-py2.7-win32.egg\pandas\core\generic.py", line 10
8, in _validate_dtype
    dtype = np.dtype(dtype)
TypeError: data type "product3" not understood

And I'm not quite sure why... Help is much appreciated! 而且我不太确定为什么...非常感谢您的帮助!

You are constructing your df incorrectly, the following would work: 您错误地构建了df,以下方法将起作用:

In [3]:

df = pd.DataFrame(columns=["prices", "product1", "product2", "product3"])
df.prices = ["Price Option 1", "Price Option 2", "Price Option 3"]
df.product1 = [1,2,3]
df.product2 = [4,5,6]
df.product3 = [7,8,9]
df
Out[3]:
           prices  product1  product2  product3
0  Price Option 1         1         4         7
1  Price Option 2         2         5         8
2  Price Option 3         3         6         9

As would putting your data into a dict: 就像将数据放入字典一样:

In [4]:

data = {'prices':["Price Option 1", "Price Option 2", "Price Option 3"], 'product1':[1,2,3], 'product2':[4,5,6], 'product3':[7,8,9]}
pd.DataFrame(data)
Out[4]:
           prices  product1  product2  product3
0  Price Option 1         1         4         7
1  Price Option 2         2         5         8
2  Price Option 3         3         6         9

You can then write to csv as normal 然后您可以照常写入csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM