【问题标题】:Using Pandas to_csv function使用 Pandas to_csv 函数
【发布时间】:2014-12-23 00:45:16
【问题描述】:

我一直在尝试使用 pandas,虽然我已经弄清楚如何使用它来读取数据,但我在编写输出时遇到了一些麻烦,需要您的帮助!

这是我的简化代码:

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") 

预期的输出应该是这样的:

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

但是我得到了这个错误:

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

我不太确定为什么...非常感谢您的帮助!

【问题讨论】:

  • 您的代码没有运行,您构建 df 的方式存在问题,不要介意尝试将其写入 csv。您正在尝试创建的 df 是您所显示的预期输出吗?
  • 您好,埃德,感谢您的回复。是的,这不起作用,预期的输出是我认为我的代码会产生的。似乎我需要某种需要进行的数据验证,但我无法找到解决方法,我似乎找不到解决此问题的教程。

标签: python python-2.7 csv pandas export-to-csv


【解决方案1】:

您的 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

将您的数据放入字典中:

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

然后您可以正常写入 csv

【讨论】:

  • 啊,好吧,我看到了如何将列正确定义为参数的细微差别。非常感谢!
  • 我认为您的根本误解是如何为列分配值,它应该是通过属性或键所以df.product1 或df['product1']
猜你喜欢
  • 2018-08-03
  • 1970-01-01
  • 1970-01-01
  • 2020-03-16
  • 2013-06-25
  • 2018-05-18
  • 2014-02-04
  • 2019-05-06
相关资源
最近更新 更多