python編碼及型別轉換

2022-08-09 10:24:07 字數 1019 閱讀 5989

使用chardet模組來判斷資料的編碼;輸入引數為str型別。

#

coding:utf-8

import

chardet

f =open('

hadoop.txt

','r

') #

開啟文字檔案,唯讀

about=f.read() #

讀取文字內容

print cchardet.detect(about) #

判斷字串編碼

#將字串的原編碼先轉成unicode編碼,再轉成utf-8編碼

print about.decode('

gbk').encode('

utf-8

')

pd.dataframe資料型別轉換

#

-*- coding: utf-8 -*-

import

pandas as pd

df = pd.dataframe([, ])

print

dfprint

'檢視df物件資料型別

'print

df.dtypes

df['

col2

'] = df['

col2

'].astype('

int'

)print

'-------------------------------------------

'print df['

col2

'] .dtypes

df['

col2

'] = df['

col2

'].astype('

float64')

print

'-------------------------------------------

'print df.dtypes

當然方法還有很多。。。

python 字元編碼識別及轉換

python教程 如何檢視字串編碼 python isinstance 函式 python字串編碼 import chardet str1 你好啊!print chardet.detect str1 輸出如下。python 2.x 預設的字元編碼是 ascii,預設的檔案編碼也是 ascii。pyt...

python變數 型別及轉換

python變數 python變數就是指 在執行過程中可能會發生變化的量,這個可能發生變化的量被稱為變數。通常情況下 變數名稱等於變數值。那麼這個變數需要滿足那些規則呢?讓我們一起來學習。變數又稱為識別符號,在python中變數滿足下列規則 1 變數名稱必須使用有效字元,有效字元可以是英文本母 英文...

Python3 各編碼型別轉換

源 轉碼規則 utf 8 decode unicode utf 8 encode unicode gbk decode unicode gbk encode unicode import sys print sys.getdefaultencoding 字串要先手動 encode指定其為某一編碼的位...