从pd.DataFrame设置数据类型时出现TypeError: object of type 'type' has no len()错误

5
假设我有一个数据框,并且想要像调用read_csv方法一样设置所有列的数据类型。为了简化,下面是一个代码片段,它会返回错误信息TypeError: object of type 'type' has no len():
df = pd.DataFrame([1,2,2,3], columns = ['num'], dtype={'num':int})

这里有什么问题,如何使它正常工作?
完整错误栈:
TypeError                                 Traceback (most recent call last)
<ipython-input-42-e8a84bf74364> in <module>()
----> 1 df = pd.DataFrame([1,2,2,3], columns = ['num'], dtype={'num':int})

C:\Anaconda3\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy)
    264             data = {}
    265         if dtype is not None:
--> 266             dtype = self._validate_dtype(dtype)
    267 
    268         if isinstance(data, DataFrame):

C:\Anaconda3\lib\site-packages\pandas\core\generic.py in _validate_dtype(self, dtype)
    145 
    146         if dtype is not None:
--> 147             dtype = pandas_dtype(dtype)
    148 
    149             # a compound dtype

C:\Anaconda3\lib\site-packages\pandas\core\dtypes\common.py in pandas_dtype(dtype)
   1895 
   1896     try:
-> 1897         npdtype = np.dtype(dtype)
   1898     except (TypeError, ValueError):
   1899         raise

C:\Anaconda3\lib\site-packages\numpy\core\_internal.py in _usefields(adict, align)
     60         names = None
     61     if names is None:
---> 62         names, formats, offsets, titles = _makenames_list(adict, align)
     63     else:
     64         formats = []

C:\Anaconda3\lib\site-packages\numpy\core\_internal.py in _makenames_list(adict, align)
     28     for fname in fnames:
     29         obj = adict[fname]
---> 30         n = len(obj)
     31         if not isinstance(obj, tuple) or n not in [2, 3]:
     32             raise ValueError("entry not a 2- or 3- tuple")

TypeError: object of type 'type' has no len()

这意味着obj是一种类型。例如,intstr...在您的情况下,您将int传递给了dtype。我建议您仔细阅读文档,以获取正确的输入参数格式。 - Seaky Lone
1个回答

7

文档中引用:

dtype:dtype,默认值为None 要强制使用的数据类型。仅允许一个数据类型。如果为None,则推断。

简而言之,您必须仅指定一种dtype,并且不能传递字典。

文档示例...

df = pd.DataFrame(data=d, dtype=np.int8)
df.dtypes
#col1    int8
#col2    int8
#dtype: object

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接