我一直在试验大熊猫,虽然我已经想出如何使用它来读取数据,但我在编写输出时遇到了一些麻烦,需要你的帮助!
这是我的简化代码:
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
我不太清楚为什么......非常感谢帮助!
答案 0 :(得分: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
将数据放入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
然后您可以正常写入csv