pandas - 将df.index从float64更改为Unicode或字符串

85
我想将一个数据框的索引(行)从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)

错误信息:

TypeError: Setting <class 'pandas.core.index.Float64Index'> dtype to anything other than float64 or object is not supported
3个回答

136

您可以这样做:

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

至于为什么在从int转换为float时需要以不同方式进行,这是numpy(pandas基于的库)的一种特殊性。

每个numpy数组都有一个“dtype”,它基本上是其元素的“机器”类型:因此,numpy直接处理本地类型,而不是Python对象,这解释了它为什么如此快速。因此,当您从int64更改为float64的dtype时,numpy将在C代码中对每个元素进行转换。

还有一种特殊的dtype:object,它基本上提供指向Python对象的指针。

如果您想要字符串,则必须使用 dtype。但是使用.astype(object)不会得到您要查找的答案:它将创建具有对象dtype的索引,但放置Python浮点对象内部。

在这里,通过使用map,我们使用适当的函数将索引转换为字符串:numpy获取字符串对象并理解索引必须具有 dtype,因为那是唯一可以容纳字符串的dtype。


1
这在Python 3.5上不起作用。你有任何想法为什么吗? - Shivam Gaur
3
原始作者使用的是 Python 2。在 Python 3 中,unicode 类型已经不存在了,必须使用 str 类型代替(基本上,在 Python 2 中称为 str 的东西,在 Python 3 中被称为 bytes,而 unicode 同样变成了 str)。 更多信息请参见这个问题 - Salomé
我在Python 3中尝试了这个,但它没有改变任何东西。我正在尝试将一个索引从Object更改为String。 - PMcK
@ PMcK 我遇到了同样的问题。 有成功解决吗? - AndreaCassioli

17

对于Python 3和Pandas 0.19或更高版本,我发现以下内容适用于我的情况。

# Python 3 (pandas 0.19 or latter versions)
df.index.astype(str, copy = False)

5
有时需要使用 df.index = df.index.astype(int) 而不是 copy=False - Michel de Ruiter
1
@MicheldeRuiter,您能告诉我何时需要使用赋值而不是copy=False吗? - VaM999
@VaM999 我不记得了... :-( - Michel de Ruiter
当我使用copy=False并且类型为np.uint64时,出现了问题,输出将不再是无符号的。 - Olivierwa
1
这在 Python 3.8/pandas 1.3.4 上不起作用,无论是 copy=True 还是 False。你能重新检查并确认哪些版本可以使用吗? - smci

3

对我来说,这是最好的方法:

df.index = df.index.astype('int64')

其中int64可以更改为其他类型。


1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

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