source

pandas - df.index를 float64에서 유니코드 또는 문자열로 변경

factcode 2023. 10. 21. 10:53
반응형

pandas - df.index를 float64에서 유니코드 또는 문자열로 변경

데이터 프레임의 인덱스(행)를 float64에서 문자열 또는 유니코드로 변경합니다.

나는 이것이 효과가 있을 것이라 생각했지만 분명히 그렇지 않습니다.

#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

그렇게 할 수 있습니다.

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

왜 당신이 부유물로 전환할 때와 다르게 진행할 것인지에 관해 말하자면, 그것이 Numpy(판다가 기반을 둔 도서관)의 특징입니다.

모든 numpy 배열에는 기본적으로 요소의 기계 유형인 dtype이 있습니다. 그런 방식으로 numpy는 파이썬 개체가 아니라 네이티브 유형을 직접 다루는데, 이것은 numpy가 얼마나 빠른지를 설명해줍니다.그래서 당신이 dtype을 int64에서 float64로 변경할 때, numpy는 C 코드의 각 요소를 캐스트합니다.

기본적으로 파이썬 객체에 대한 포인터를 제공하는 특별한 dtype : object도 있습니다.

문자열을 사용하려면 개체 dtype을 사용해야 합니다.하지만 사용..astype(object)대신 objectdtype으로 인덱스를 만들고 내부에 Python float objects를 넣을 수 있습니다.

여기서는 맵을 사용하여 인덱스를 적절한 함수를 가진 문자열로 변환합니다. numpy는 문자열 개체를 가져오고, 문자열을 수용할 수 있는 유일한 dtype이기 때문에 인덱스에 개체 dtype이 있어야 한다는 것을 이해합니다.

python 3 버전과 panda 0.19 이상 버전의 경우, 다음과 같은 작업이 저에게 적합합니다.

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

저는 이 방법이 가장 효과적입니다.

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

여기서 다른 유형으로 변경할 수 있습니다.

언급URL : https://stackoverflow.com/questions/35368645/pandas-change-df-index-from-float64-to-unicode-or-string

반응형