Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python - Pandas DataFrame에서 한 데이터 유형을 다른 데이터 유형으로 변환

<시간/>

Pandas에서 astype() 메서드를 사용하여 한 데이터 유형을 다른 데이터 유형으로 변환합니다. 필요한 라이브러리 가져오기 -

pandas를 pd로 가져오기

데이터프레임을 생성합니다. 여기에 2개의 열이 있습니다. "Reg_Price"는 float 유형이고 "Units"는 int 유형입니다 -

dataFrame =pd.DataFrame( { "등록 가격":[7000.5057, 1500, 5000, 8000, 9000.75768, 6000], "단위":[90, 120, 100, 150, 300]),> 

위에서 생성된 열의 데이터 유형을 확인하십시오 -

dataFrame.dtypes

두 유형을 모두 int32로 변환 -

dataFrame.astype('int32').dtypes

다음은 코드입니다 -

판다를 pd로 가져오기# Create DataFramedataFrame =pd.DataFrame( { "Reg_Price":[7000.5057, 1500, 5000, 8000, 9000.75768, 6000], "단위":[90, 0,20, 5, 10 ] })print"DataFrame ...\n",dataFrameprint"\nDataFrame 유형 ...\n",dataFrame.dtypesprint"\n모든 열을 int32로 캐스트..."print"\n업데이트된 DataFrame 유형 ...\n ",dataFrame.astype('int32').dtypes

출력

이것은 다음과 같은 출력을 생성합니다 -

 DataFrame ... Reg_Price Units0 7000.5000.5000.5000.500000 1003 8000.00000 1504 9000.75768 2005 6000.00000 130DataFrame 유형 ... reg_price float64units int64dtype :objectstalls in int32 ... reg_price int32units int32dtype :object