Python酷庫之旅-第三方庫Pandas(024)

目錄

一、用法精講

61、pandas.to_numeric函數

61-1、語法

61-2、參數

61-3、功能

61-4、返回值

61-5、說明

61-6、用法

61-6-1、數據準備

61-6-2、代碼示例

61-6-3、結果輸出

62、pandas.to_datetime函數

62-1、語法

62-2、參數

62-3、功能

62-4、返回值

62-5、說明

62-6、用法

62-6-1、數據準備

62-6-2、代碼示例

62-6-3、結果輸出?

二、推薦閱讀

1、Python筑基之旅

2、Python函數之旅

3、Python算法之旅

4、Python魔法之旅

5、博客個人主頁
???????

一、用法精講

61、pandas.to_numeric函數
61-1、語法
# 61、pandas.to_numeric函數
pandas.to_numeric(arg, errors='raise', downcast=None, dtype_backend=_NoDefault.no_default)
Convert argument to a numeric type.The default return dtype is float64 or int64 depending on the data supplied. Use the downcast parameter to obtain other dtypes.Please note that precision loss may occur if really large numbers are passed in. Due to the internal limitations of ndarray, if numbers smaller than -9223372036854775808 (np.iinfo(np.int64).min) or larger than 18446744073709551615 (np.iinfo(np.uint64).max) are passed in, it is very likely they will be converted to float so that they can be stored in an ndarray. These warnings apply similarly to Series since it internally leverages ndarray.Parameters:
argscalar, list, tuple, 1-d array, or Series
Argument to be converted.errors{‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’
If ‘raise’, then invalid parsing will raise an exception.If ‘coerce’, then invalid parsing will be set as NaN.If ‘ignore’, then invalid parsing will return the input.Changed in version 2.2.“ignore” is deprecated. Catch exceptions explicitly instead.downcaststr, default None
Can be ‘integer’, ‘signed’, ‘unsigned’, or ‘float’. If not None, and if the data has been successfully cast to a numerical dtype (or if the data was numeric to begin with), downcast that resulting data to the smallest numerical dtype possible according to the following rules:‘integer’ or ‘signed’: smallest signed int dtype (min.: np.int8)‘unsigned’: smallest unsigned int dtype (min.: np.uint8)‘float’: smallest float dtype (min.: np.float32)As this behaviour is separate from the core conversion to numeric values, any errors raised during the downcasting will be surfaced regardless of the value of the ‘errors’ input.In addition, downcasting will only occur if the size of the resulting data’s dtype is strictly larger than the dtype it is to be cast to, so if none of the dtypes checked satisfy that specification, no downcasting will be performed on the data.dtype_backend{‘numpy_nullable’, ‘pyarrow’}, default ‘numpy_nullable’
Back-end data type applied to the resultant DataFrame (still experimental). Behaviour is as follows:"numpy_nullable": returns nullable-dtype-backed DataFrame (default)."pyarrow": returns pyarrow-backed nullable ArrowDtype DataFrame.New in version 2.0.Returns:
ret
Numeric if parsing succeeded. Return type depends on input. Series if Series, otherwise ndarray.
61-2、參數

61-2-1、arg(必須)表示你想要轉換的數據,可以是一個單獨的數值、列表、Series或者DataFrame。

61-2-2、errors(可選,默認值為'raise')指定在遇到不能轉換為數字的值時的處理方式,可選的值有:

61-2-2-1、'raise'(默認值):遇到錯誤時會引發異常。

61-2-2-2、'coerce':遇到不能轉換為數字的值時,將其轉換為NaN(缺失值)。

61-2-2-3、'ignore':忽略不能轉換為數字的值,保持原樣。

61-2-3、downcast(可選,默認值為None)用于將數據轉換為較低精度的數值類型,以減少內存使用,可選值有:

61-2-3-1、None(默認值):不進行降級。

61-2-3-2、'integer':盡可能轉換為較小的整數類型。

61-2-3-3、'signed':盡可能轉換為較小的有符號整數類型。

61-2-3-4、'unsigned':盡可能轉換為較小的無符號整數類型。

61-2-3-5、'float':盡可能轉換為較小的浮點數類型。

61-2-4、dtype_backend(可選)內部調用,一般不需要用戶直接設置。

61-3、功能

????????用于將參數(如單個值、列表、Series或者DataFrame)中的數據轉換為數字類型(整數或浮點數)。

61-4、返回值

????????函數的返回值取決于輸入數據的類型:

61-4-1、單個值:如果輸入是單個值,返回一個轉換后的數值(整數或浮點數)。

61-4-2、列表:如果輸入是列表,返回一個包含轉換后數值的列表。

61-4-3、Series:如果輸入是pandas Series,返回一個轉換后的pandas Series,類型為數值類型。

61-4-4、DataFrame:如果輸入是pandas DataFrame,返回一個轉換后的DataFrame,每一列都會嘗試轉換為數值類型。

61-5、說明

????????該函數通過靈活的參數設置,能夠有效地將不同類型的數據轉換為數值類型,并提供多種錯誤處理選項,適用于數據預處理和清洗的各類場景。

61-6、用法
61-6-1、數據準備
61-6-2、代碼示例
# 61、pandas.to_numeric函數
# 61-1、轉換Series
import pandas as pd
data = pd.Series(['1', '2', '3', 'apple', '5'])
# 轉換為數字,遇到錯誤將其轉換為NaN
numeric_data = pd.to_numeric(data, errors='coerce')
print(numeric_data, end='\n\n')# 61-2、轉換DataFrame
import pandas as pd
df = pd.DataFrame({'A': ['1', '2', '3', 'apple', '5'],'B': ['10.5', '20.1', '30.2', '40.0', '50.5']
})
# 轉換為數字,遇到錯誤將其轉換為NaN
numeric_df = df.apply(pd.to_numeric, errors='coerce')
print(numeric_df)
61-6-3、結果輸出
# 61、pandas.to_numeric函數
# 61-1、轉換Series
# 0    1.0
# 1    2.0
# 2    3.0
# 3    NaN
# 4    5.0
# dtype: float64# 61-2、轉換DataFrame
#      A     B
# 0  1.0  10.5
# 1  2.0  20.1
# 2  3.0  30.2
# 3  NaN  40.0
# 4  5.0  50.5
62、pandas.to_datetime函數
62-1、語法
# 62、pandas.to_datetime函數
pandas.to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=False, format=None, exact=_NoDefault.no_default, unit=None, infer_datetime_format=_NoDefault.no_default, origin='unix', cache=True)
Convert argument to datetime.This function converts a scalar, array-like, Series or DataFrame/dict-like to a pandas datetime object.Parameters:
argint, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like
The object to convert to a datetime. If a DataFrame is provided, the method expects minimally the following columns: "year", "month", "day". The column “year” must be specified in 4-digit format.errors{‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’
If 'raise', then invalid parsing will raise an exception.If 'coerce', then invalid parsing will be set as NaT.If 'ignore', then invalid parsing will return the input.dayfirstbool, default False
Specify a date parse order if arg is str or is list-like. If True, parses dates with the day first, e.g. "10/11/12" is parsed as 2012-11-10.Warningdayfirst=True is not strict, but will prefer to parse with day first.yearfirstbool, default False
Specify a date parse order if arg is str or is list-like.If True parses dates with the year first, e.g. "10/11/12" is parsed as 2010-11-12.If both dayfirst and yearfirst are True, yearfirst is preceded (same as dateutil).Warningyearfirst=True is not strict, but will prefer to parse with year first.utcbool, default False
Control timezone-related parsing, localization and conversion.If True, the function always returns a timezone-aware UTC-localized Timestamp, Series or DatetimeIndex. To do this, timezone-naive inputs are localized as UTC, while timezone-aware inputs are converted to UTC.If False (default), inputs will not be coerced to UTC. Timezone-naive inputs will remain naive, while timezone-aware ones will keep their time offsets. Limitations exist for mixed offsets (typically, daylight savings), see Examples section for details.WarningIn a future version of pandas, parsing datetimes with mixed time zones will raise an error unless utc=True. Please specify utc=True to opt in to the new behaviour and silence this warning. To create a Series with mixed offsets and object dtype, please use apply and datetime.datetime.strptime.See also: pandas general documentation about timezone conversion and localization.formatstr, default None
The strftime to parse time, e.g. "%d/%m/%Y". See strftime documentation for more information on choices, though note that "%f" will parse all the way up to nanoseconds. You can also pass:“ISO8601”, to parse any ISO8601 time string (not necessarily in exactly the same format);“mixed”, to infer the format for each element individually. This is risky, and you should probably use it along with dayfirst.NoteIf a DataFrame is passed, then format has no effect.exactbool, default True
Control how format is used:If True, require an exact format match.If False, allow the format to match anywhere in the target string.Cannot be used alongside format='ISO8601' or format='mixed'.unitstr, default ‘ns’
The unit of the arg (D,s,ms,us,ns) denote the unit, which is an integer or float number. This will be based off the origin. Example, with unit='ms' and origin='unix', this would calculate the number of milliseconds to the unix epoch start.infer_datetime_formatbool, default False
If True and no format is given, attempt to infer the format of the datetime strings based on the first non-NaN element, and if it can be inferred, switch to a faster method of parsing them. In some cases this can increase the parsing speed by ~5-10x.Deprecated since version 2.0.0: A strict version of this argument is now the default, passing it has no effect.originscalar, default ‘unix’
Define the reference date. The numeric values would be parsed as number of units (defined by unit) since this reference date.If 'unix' (or POSIX) time; origin is set to 1970-01-01.If 'julian', unit must be 'D', and origin is set to beginning of Julian Calendar. Julian day number 0 is assigned to the day starting at noon on January 1, 4713 BC.If Timestamp convertible (Timestamp, dt.datetime, np.datetimt64 or date string), origin is set to Timestamp identified by origin.If a float or integer, origin is the difference (in units determined by the unit argument) relative to 1970-01-01.cachebool, default True
If True, use a cache of unique, converted dates to apply the datetime conversion. May produce significant speed-up when parsing duplicate date strings, especially ones with timezone offsets. The cache is only used when there are at least 50 values. The presence of out-of-bounds values will render the cache unusable and may slow down parsing.Returns:
datetime
If parsing succeeded. Return type depends on input (types in parenthesis correspond to fallback in case of unsuccessful timezone or out-of-range timestamp parsing):scalar: Timestamp (or datetime.datetime)array-like: DatetimeIndex (or Series with object dtype containing datetime.datetime)Series: Series of datetime64 dtype (or Series of object dtype containing datetime.datetime)DataFrame: Series of datetime64 dtype (or Series of object dtype containing datetime.datetime)Raises:
ParserError
When parsing a date from string fails.ValueError
When another datetime conversion error happens. For example when one of ‘year’, ‘month’, day’ columns is missing in a DataFrame, or when a Timezone-aware datetime.datetime is found in an array-like of mixed time offsets, and utc=False.
62-2、參數

62-2-1、arg(必須)表示需要轉換為日期時間的對象,可以是單個日期時間字符串、日期時間對象、列表、Series或DataFrame。

62-2-2、errors(可選,默認值為'raise')指定在遇到不能轉換為數字的值時的處理方式,可選的值有:

62-2-2-1、'raise'(默認值):遇到錯誤時會引發異常。

62-2-2-2、'coerce':遇到不能轉換為數字的值時,將其轉換為NaN(缺失值)。

62-2-2-3、'ignore':忽略不能轉換為數字的值,保持原樣。

62-2-3、dayfirst(可選,默認值為False)當為True時,解析日期時優先將前兩位作為日,例如:dayfirst=True將'10/11/2024'解析為2024年11月10日。

62-2-4、yearfirst(可選,默認值為False)當為True時,解析日期時優先將前兩位作為年,例如:yearfirst=True將'2024-10-11'解析為2024年10月11日。

62-2-5、utc(可選,默認值為False)當為True時,將時間轉換為UTC時間。

62-2-6、format(可選,默認值為None)指定日期時間字符串的格式,例如:format='%Y-%m-%d %H:%M:%S'。

62-2-7、exact(可選)當為True時,要求日期時間字符串完全匹配格式。

62-2-8、unit(可選,默認值為None)如果傳入的是整數或浮點數,指定其時間單位,如s(秒),ms(毫秒),us(微秒),ns(納秒)。

62-2-9、infer_datetime_format(可選)當為True時,自動推斷日期時間字符串的格式以提高解析速度。

62-2-10、origin(可選,默認值為'unix')指定時間計算的起點,可以是'unix'(1970-01-01),也可以是具體的時間字符串。

62-2-11、cache(可選,默認值為True)當為True時,啟用緩存以提高解析速度。

62-3、功能

????????用于將各種格式的輸入數據轉換為datetime64[ns]類型,確保數據在后續分析中具有一致的日期時間格式。

62-4、返回值

????????返回值類型取決于輸入:

62-4-1、如果輸入是單個字符串或單個數值,則返回一個Timestamp對象。

62-4-2、如果輸入是列表、數組、Series或DataFrame,則返回一個DatetimeIndex或Series,其中包含轉換后的日期時間數據。

62-5、說明

? ? ? ? 無

62-6、用法
62-6-1、數據準備
62-6-2、代碼示例
# 62、pandas.to_datetime函數
# 62-1、將字符串轉換為datetime
import pandas as pd
date_str = '2024-07-15'
date = pd.to_datetime(date_str)
print(date, end='\n\n')# 62-2:將列表轉換為datetime
import pandas as pd
date_list = ['2024-07-15', '2025-07-15']
dates = pd.to_datetime(date_list)
print(dates, end='\n\n')# 62-3:處理Series并處理錯誤
import pandas as pd
date_series = pd.Series(['2024-07-15', '2025-07-15', 'not a date'])
dates = pd.to_datetime(date_series, errors='coerce')
print(dates, end='\n\n')# 62-4:使用特定格式解析日期
import pandas as pd
date_str = '15/07/2024'
date = pd.to_datetime(date_str, format='%d/%m/%Y', dayfirst=True)
print(date, end='\n\n')# 62-5:將時間戳轉換為datetime
import pandas as pd
timestamp_series = pd.Series([1626357600, 1626358200])
dates = pd.to_datetime(timestamp_series, unit='s')
print(dates)
62-6-3、結果輸出?
# 62、pandas.to_datetime函數
# 62-1、將字符串轉換為datetime
# 2024-07-15 00:00:00# 62-2:將列表轉換為datetime
# DatetimeIndex(['2024-07-15', '2025-07-15'], dtype='datetime64[ns]', freq=None)# 62-3:處理Series并處理錯誤
# 0   2024-07-15
# 1   2025-07-15
# 2          NaT
# dtype: datetime64[ns]# 62-4:使用特定格式解析日期
# 2024-07-15 00:00:00# 62-5:將時間戳轉換為datetime
# 0   2021-07-15 14:00:00
# 1   2021-07-15 14:10:00
# dtype: datetime64[ns]

二、推薦閱讀

1、Python筑基之旅
2、Python函數之旅
3、Python算法之旅
4、Python魔法之旅
5、博客個人主頁

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/45313.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/45313.shtml
英文地址,請注明出處:http://en.pswp.cn/web/45313.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

關于SQLException: Illegal mix of collations (`utf8mb4_general_ci,IMPLICIT`)...錯誤

希望文章能給到你啟發和靈感~ 如果覺得文章對你有幫助的話,點贊 關注 收藏 支持一下博主吧~ 閱讀指南 開篇說明一、基礎環境說明1.1 硬件環境1.2 軟件環境 二、報錯信息三、最后 開篇說明 記錄一個查詢錯誤 場景:數據庫之間某表復…

曠野之間 16 – AI 代理、AI 代理基礎設施、平臺和比較

在本文中,我們將研究 AI 代理、AI 代理基礎設施、市場上最流行的 AI 代理平臺、它們的比較以及 AI 代理的未來 我們將按以下順序討論這些主題 1. 關于人工智能代理 2. 人工智能代理在行業中的應用 3. AI代理基礎設施 4. 最受歡迎的 AI 代理平臺及比較 5.您將如…

【筆記】nginx命令

查看 啟動 通過./nginx啟動nginx之后 可以在虛擬機中進入/usr/local/nginx/html 去查看cat index.html 也就是此頁面的源代碼 進入vim /etc/profile 配置完之后保存退出 source /etc/profile 手動重載資源 隨后就可以在任意位置重載資源了 nginx -s reload 部署靜態資源就把靜…

兩項國際設計獎,支持雙設備—悠律Ringbuds pro開放式藍牙耳機體驗

在音頻設備領域,開放式耳機對比入耳式耳機的優勢就是既能聽到耳機內的聲音又能感知環境音,很適合在戶外以及辦公時使用,今天分享一款新品牌悠律UMELODY——悠律凝聲環Ringbuds pro,它采用氣傳導耳掛式設計,佩戴舒適、安…

【人工智能】 知識表示與推理(八數碼 + 傳教士與野人渡河)

目錄 一、八數碼難題 1. 需求分析 2. 數據結構、功能模塊設計與說明 2.1 算法思路 2.2 數據結構 3. 核心代碼與測試結果說明 3.1 核心代碼 3.2 測試結果說明 4. 存在的問題與體會 4.1 存在的問題 4.2 體會 二、傳教士與野人渡河 1. 需求分析 2. 數據結構、功能模…

基于EMQX+Flask+InfluxDB+Grafana打造多協議物聯網云平臺:MQTT/HTTP設備接入與數據可視化流程(附代碼示例)

摘要: 本文深入淺出地介紹了物聯網、云平臺、MQTT、HTTP、數據可視化等核心概念,并結合 EMQX、Flask、InfluxDB、Grafana 等主流工具,手把手教你搭建一個支持多協議的物聯網云平臺。文章結構清晰,圖文并茂,代碼翔實易懂&#xff0…

2024-07-14 Unity插件 Odin Inspector1 —— 插件介紹

文章目錄 1 介紹2 模塊3 學習目的 1 介紹 ? Odin Inspector 是 Unity 的一個插件,擁有強大、自定義和用戶友好的編輯器,而無需編寫任何自定義編輯器代碼,使得編程過程中的數據可視化更容易實現。 ? 具體功能包括: 更舒適美觀…

軟件設計師(中級)備考視頻教程

一、視頻介紹 本視頻主要包括軟件設計師系統學習教程,通過學習本視頻,可以幫助考生高效且深入地掌握軟件設計師資格考試核心知識,全方位覆蓋考試要點,從而輕松備戰考試。視頻不僅涵蓋了考試所需的全面知識體系,還通過直…

Linux--USB驅動開發(二)插入USB后的內核執行程序

一、USB總線驅動程序的作用 a)識別USB設備 1.1 分配地址 1.2 并告訴USB設備(set address) 1.3 發出命令獲取描述符 b)查找并安裝對應的設備驅動程序 c)提供USB讀寫函數 二、USB設備工作流程 由于內核自帶了USB驅動,所以我們先插入一個U…

Google Colab 云端硬盤路徑讀取

加載云端硬盤 需要在左上角點擊這個文件圖標; from google.colab import drive drive.mount("/content/drive") # 掛載云端硬盤import os path"/content/drive/MyDrive/TextClassificationCustom" os.chdir(path) # 以路徑path作為當前工作目…

在 SwiftUI 中的作用域動畫

文章目錄 前言簡單示例動畫視圖修飾符使用多個可動畫屬性使用 ViewBuilder總結 前言 從一開始,動畫就是 SwiftUI 最強大的功能之一。你可以在 SwiftUI 中快速構建流暢的動畫。唯一的缺點是每當我們需要運行多步動畫或將動畫范圍限定到視圖層次結構的特定部分時&…

docker emqx 配置密碼和禁用匿名連接

mqtt版本emqx/emqx:4.4.3 1.首先把鏡像內目錄/opt/emqx/etc拷貝到本地 2.做映射 3.allow_anonymous, false改成true 4. 5.MQTTX連不上的話看看下圖的有沒有打開

【nginx】nginx的優點

目錄 一、高性能1.1 高并發處理1.2 低內存消耗1.3 快速響應 二、高擴展性2.1 模塊化設計2.2 動態模塊擴展 三、高可靠性3.1 核心框架穩定3.2 進程管理3.3 負載均衡與健康檢查3.4 熱部署 四、功能豐富4.1 反向代理4.2 HTTP緩存4.3 安全功能 五、易于配置和管理5.1 配置文件簡單5…

windows下環境變量開啟方式

第一種方法: 使用快捷鍵打開“運行”對話框:按下 Win R 組合鍵,這將打開“運行”窗口。 輸入系統屬性命令:在“運行”窗口中輸入 sysdm.cpl 然后按回車鍵。這將打開“系統屬性”對話框。【sysdm.cpl是"System Data Manager…

【Go系列】Go的指針

承上啟下 我們在前面的文章中,首先介紹了GO的基礎語法,然后介紹了Goroutine和channel這個最具有特色的東西,同時介紹了Sync和context,以及在上篇文章中詳細距離說明了Go里面用于高并發的多種寫法。基礎的使用方法也告一段落了&…

Linux多線程編程-哲學家就餐問題詳解與實現(C語言)

在哲學家就餐問題中,假設有五位哲學家圍坐在圓桌前,每位哲學家需要進行思考和進餐兩種活動。他們的思考不需要任何資源,但進餐需要使用兩根筷子(左右兩側各一根)。筷子是共享資源,哲學家們在進行進餐時需要…

Qt qml詳細介紹

一.基本類型 QML的基本類型包括了很多不同的類型,這些類型可以用于定義用戶界面元素、屬性和信號。以下是一些常用的QML基本類型及其詳細介紹: 數值類型:包括整數類型(int、uint、short、ushort等)和浮點數類型&#…

c++ :運算符重載函數中的細節

賦值運算符重載與拷貝構造函數 (1)區分初始化時的賦值(一般就叫初始化),和非初始化時的賦值(一般就叫賦值) (2)實驗驗證初始化和賦值時各自對應 避免賦值運算符中的自賦值 (1)自賦值就是Person a; a a; (2)自賦值如…

鞭炮插畫:成都亞恒豐創教育科技有限公司

鞭炮插畫:年味里的絢爛記憶 在歲末年初的溫柔時光里,總有一抹色彩,能瞬間喚醒沉睡的年味——那便是鞭炮插畫中躍動的紅與金,成都亞恒豐創教育科技有限公司 它們不僅僅是紙與墨的交織,更是情感與記憶的橋梁&#xff0c…

自適應手機版大學職業技術學院網站模版源碼系統 帶完整的安裝代碼包以及搭建部署教程

系統概述 隨著智能手機的普及和移動互聯網技術的飛速發展,用戶越來越傾向于通過移動設備訪問網站。對于大學職業技術學院而言,一個能夠自適應各種屏幕尺寸、操作流暢、內容豐富的移動端網站,不僅能夠提升用戶體驗,還能有效擴大學…