使用 df.replace 可以用除np.nan/None之外的任何值替換pd.NaT
注意:我必須在使用 fillna('') 的地方進行多次資料轉換,這在 NaT 上不起作用,而且我不希望鏈式替換,因為它在大量資料幀上有點貴。
我有一個 df(在 dtype 資訊之后提供)
ID int64
TYPE object
NAME object
LOCATION_ID float64
COUNTRY_ID float64
REGION_ID float64
SLA_TIME_TO_FIRST_RESPONSE_START_TIME datetime64[ns]
SLA_TIME_TO_FIRST_RESPONSE_STOP_TIME datetime64[ns]
SLA_TIME_TO_RESOLUTION_START_TIME datetime64[ns]
SLA_TIME_TO_RESOLUTION_STOP_TIME datetime64[ns]

df.replace(pd.NaT,np.nan)
不會將 NaT 替換為 NaN

df.replace(pd.NaT, 'anything')
將 NaT 替換為“任何東西”

uj5u.com熱心網友回復:
pandas總體上存在一些型別問題,這就是為什么這些pd.NaT和“pd.NA”適用的原因。以下是使用帶有bool型別的列時的問題示例。在創建DataFrame一列bool_type僅包含布林值的位置后,型別為“布爾”,而另一列boot_with_none包含布林值和“無”值的型別為“物件”。
import pandas as pd
df = pd.DataFrame({"bool_type": [True, False, True], "boot_with_none": [True, False, None]})
df.info()
# # Column Non-Null Count Dtype
# --- ------ -------------- -----
# 0 bool_type 3 non-null bool
# 1 boot_with_none 2 non-null object
print(df)
# bool_type boot_with_none
# 0 True True
# 1 False False
# 2 True None
如果我們嘗試將boot_with_none列轉換為 type bool,它會自動將 'None' 值替換為 'False'。
df["boot_with_none"] = df["boot_with_none"].astype(bool)
df.info()
# # Column Non-Null Count Dtype
# --- ------ -------------- -----
# 0 bool_type 3 non-null bool
# 1 boot_with_none 3 non-null bool
print(df)
# bool_type boot_with_none
# 0 True True
# 1 False False
# 2 True False
解決此問題的一種方法是將列型別設定為object,然后它可以保存Nones。在下面的代碼中,您可以看到一列是 type datetime64,另一列是 type object。在該replace方法之后,列型別datetime64保持為pd.NaTs 而object型別列將值更改為None。
import pandas as pd
import numpy as np
df = pd.DataFrame({'original_type': [np.datetime64("2018-01-01"), np.datetime64("2018-01-02"), None]})
df["object_type"] = df["original_type"].astype(object)
df.info()
# # Column Non-Null Count Dtype
# --- ------ -------------- -----
# 0 original_type 2 non-null datetime64[ns]
# 1 object_type 2 non-null object
df["original_type"] = df["original_type"].replace(pd.NaT, None)
df["object_type"] = df["object_type"].replace(pd.NaT, None)
print(df)
# original_type object_type
# 0 2018-01-01 2018-01-01 00:00:00
# 1 2018-01-02 2018-01-02 00:00:00
# 2 NaT None
編輯
第二個問題是與np.nan. 作為type(np.nan) == float,它應該在float型別列(或“物件”型別列)中。此示例顯示了在將其中一個值設定為“np.nan”后,pandas 如何自動將“int”型別列轉換為“float”型別列,并將其所有值轉換為“float”。而“物件”型別列保持不變,因為它可以保存任意型別的值。
import pandas as pd
df = pd.DataFrame({"ints": [1, 2, 3]})
df["objects"] = df["ints"].astype(object)
df["ints_with_none"] = df["ints"]
df.loc[2, "ints_with_none"] = np.nan
df.info()
# # Column Non-Null Count Dtype
# --- ------ -------------- -----
# 0 ints 3 non-null int64
# 1 objects 3 non-null object
# 2 ints_with_none 2 non-null float64
print(df)
# ints objects ints_with_none
# 0 1 1 1.0
# 1 2 2 2.0
# 2 3 3 NaN
uj5u.com熱心網友回復:
菲爾納應該作業
df.fillna('anything')
如果它不起作用,請檢查它們是否真的是 pd.NaT 物件。使用型別。
type(df.iloc[1,0])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/525448.html
標籤:Python熊猫
上一篇:替換不同列中的重復值
下一篇:洗掉資料框中的未命名列會產生錯誤
