chardet 的英文字縮寫是
“charset(字符集) detection”,
意思是編碼偵測。
chardet 是 Python 的一個套件,
可以自動判斷文字檔案的編碼方式,
通常用在處理 CSV、JSON、XML 等純文字檔案時,
可以先使用 chardet 套件來判斷檔案的編碼,
再使用正確的編碼方式進行讀取,
避免因編碼不同而導致的資料解析錯誤。
import os
import chardet
import pandas as pd
folder = r"C:\Temp"
fname = "test.txt"
fpath = os.path.join(folder,fname)
#'C:\\Temp\\test.txt'
with open(fpath, 'rb') as f:
result = chardet.detect(f.read())
# "charset(字符集) detection"
“””注意要使用rb模式開檔,
不然會出現TypeError
File C:\ProgramData\Anaconda\lib\site-packages\chardet\__init__.py:36 in detect
raise TypeError(‘Expected object of type bytes or bytearray, got: ‘
TypeError: Expected object of type bytes or bytearray, got: <class ‘str’>
“””
print("charset(字符集) detection:\n",result)
df = pd.read_csv(fpath, encoding=result['encoding'])

推薦hahow線上學習python: https://igrape.net/30afN


![Python: 如何求整個 pandas.DataFrame 中的最大值? pandas.DataFrame .max().max() ; 如何求最大值的index, columns? numpy.where(condition, [x, y, ]/) ; condition為一 bool_mask Python: 如何求整個 pandas.DataFrame 中的最大值? pandas.DataFrame .max().max() ; 如何求最大值的index, columns? numpy.where(condition, [x, y, ]/) ; condition為一 bool_mask](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2023/04/20230418154049_50.png?quality=90&zoom=2&ssl=1&resize=350%2C233)




![Python 如何用pandas.Series.nsmallest() 找到n個與target差距最小的index?再從中找到距離idxmax最近的index?避免誤抓sidelobes的index? targetIdx = (serMean-target_value).abs().nsmallest(n).index.tolist() ;Series切片: .loc[標籤名1:標籤名2] (會含標籤名2) ; .iloc[位置1:位置2] (不含位置2) Python 如何用pandas.Series.nsmallest() 找到n個與target差距最小的index?再從中找到距離idxmax最近的index?避免誤抓sidelobes的index? targetIdx = (serMean-target_value).abs().nsmallest(n).index.tolist() ;Series切片: .loc[標籤名1:標籤名2] (會含標籤名2) ; .iloc[位置1:位置2] (不含位置2)](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2023/02/20230222082954_53.png?quality=90&zoom=2&ssl=1&resize=350%2C233)


近期留言