为什么Pandas告诉我我有对象,尽管所选列中的每个项都是字符串-即使在显式转换之后也是如此。
这是我的数据帧:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 56992 entries, 0 to 56991
Data columns (total 7 columns):
id 56992 non-null values
attr1 56992 non-null values
attr2 56992 non-null values
attr3 56992 non-null values
attr4 56992 non-null values
attr5 56992 non-null values
attr6 56992 non-null values
dtypes: int64(2), object(5)
其中五个是dtype object
。我显式地将这些对象转换为字符串:
for c in df.columns:
if df[c].dtype == object:
print "convert ", df[c].name, " to string"
df[c] = df[c].astype(str)
然后,df["attr2"]
仍然有dtype object
,尽管type(df["attr2"].ix[0]
显示了str
,这是正确的。
熊猫区分int64
和float64
和object
。当没有dtype str
时,它背后的逻辑是什么?为什么str
被object
覆盖?
dtype对象来自NumPy,它描述ndarray中元素的类型。ndarray中的每个元素的字节大小必须相同。对于int64和float64,它们是8字节。但对于字符串,字符串的长度不是固定的。因此,panda没有直接在ndarray中保存字符串的字节,而是使用object ndarray来保存指向对象的指针,因此这种ndarray的数据类型是object。
下面是一个例子:
公认的答案是好的。只是想提供一个答案。文件上说:
正如前面的评论所说:“别担心,它应该是这样的。”(尽管接受的答案很好地解释了“为什么”;字符串是可变长度的)
相关问题 更多 >
编程相关推荐