Boo*_*d16 45 python indexing rows dataframe pandas
我想将数据帧的索引(行)从float64更改为string或unicode.
我认为这会起作用,但显然不是:
#check type
type(df.index)
'pandas.core.index.Float64Index'
#change type to unicode
if not isinstance(df.index, unicode):
df.index = df.index.astype(unicode)
Run Code Online (Sandbox Code Playgroud)
错误信息:
TypeError: Setting <class 'pandas.core.index.Float64Index'> dtype to anything other than float64 or object is not supported
Run Code Online (Sandbox Code Playgroud)
Art*_*hur 71
你可以这样做:
# for Python 2
df.index = df.index.map(unicode)
# for Python 3 (the unicode type does not exist and is replaced by str)
df.index = df.index.map(str)
Run Code Online (Sandbox Code Playgroud)
至于为什么你会从你从int转换为float时有所不同,这是numpy(pandas所基于的库)的特点.
每个numpy数组都有一个dtype,它基本上是它的元素的机器类型:以这种方式,numpy直接处理本机类型,而不是Python对象,这解释了它是如此之快.因此,当您将dtype从int64更改为float64时,numpy将在C代码中强制转换每个元素.
还有一个特殊的dtype:object,它基本上会提供指向Python对象的指针.
如果你想要字符串,那么你必须使用对象 dtype.但是使用.astype(object)不会给你你想要的答案:它会创建一个带有对象 dtype 的索引,但是将Python浮点对象放在里面.
这里,通过使用map,我们将索引转换为具有适当函数的字符串:numpy获取字符串对象并理解索引必须具有对象 dtype,因为这是唯一可以容纳字符串的dtype.
小智 5
对于python 3和pandas 0.19或更高版本,我发现以下对我来说很好
# Python 3 (pandas 0.19 or latter versions)
df.index.astype(str, copy = False)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48036 次 |
| 最近记录: |