[英]fillna not replacing nan values in the dataframe
我正在嘗試使用fillna()
function 替換 dataframe 列“功能”中的 nan 值。 我面臨的問題如下:
isnull()
檢測到 null 值dfcomp[dfcomp['Functional'].isnull()==True]
dfcomp['Functional'][2216]
fillna()
填充 nan 時,什么也沒有發生。 即使在運行了 fillna 語句后,我也可以重新運行第一個語句並看到相同的 2 個 nan 實例。 dfcomp['Functional']=dfcomp['Functional'].fillna(value=dfcomp['Functional'].mode())
順便說一句,我已經嘗試了兩個版本
dfcomp['Functional'].fillna(value=dfcomp['Functional'].mode(),inplace=True)
replace()
function 但沒有運氣dfcomp['Functional']=dfcomp['Functional'].replace({'nan':dfcomp['Functional'].mode()})
我的代碼有問題嗎? 為什么當isnull()
可以識別nan
時fillna()
不識別? 另外,為什么索引搜索將值顯示為nan
但是當我嘗試使用replace()
替換相同的值時沒有結果?
當我的fillna()
無法識別時,如何替換 nan 值?
本質上,問題是dfcomp['Functional'].mode()
的返回類型,這是一個單一元素pandas.Series
並且fillna()
需要與您所在的列具有相同 len 的標量或 dict/Series/DataFrame試圖填補。
您需要計算列的模式,然后將標量傳遞給fillna()
方法。
mode = dfcomp['Functional'].mode().values[0]
dfcomp['Functional'].fillna(value=mode, inplace=True)
這是Index
alignment 問題。 即使只返回一個值, pd.Series.mode
總是返回 Series 。 因此,該系列的索引是RangeIndex
(最多與模式相關的值的數量),因此當您使用.fillna
時,它會嘗試在 Index 上對齊,這通常與您的 DataFrame 不對齊。
你想 select 模態值所以使用.iloc
dfcomp['Functional'] = dfcomp['Functional'].fillna(dfcomp['Functional'].mode().iloc[0])
import pandas as pd
import numpy as np
np.random.seed(42)
df = pd.DataFrame({'foo': np.random.choice([1,2,3,np.NaN], 7)})
df['foo'].mode()
#0 3.0
#dtype: float64
# Nothing gets filled because only the row with Index 0 could possibly
# be filled and it wasn't missing to begin with
df['foo'].fillna(df['foo'].mode())
#0 3.0
#1 NaN
#2 1.0
#3 3.0
#4 3.0
#5 NaN
#6 1.0
#Name: foo, dtype: float64
# This fills the `NaN` with 3 regardless of index
df['foo'].fillna(df['foo'].mode().iloc[0])
#0 3.0
#1 3.0
#2 1.0
#3 3.0
#4 3.0
#5 3.0
#6 1.0
#Name: foo, dtype: float64
為了填充 NaN 值,您可以使用以下代碼:
dfcomp = dfcomp.fillna(value=0)
后期更新:
dfcomp['Functional'] = dfcomp['Functional'].fillna(dfcomp['mode'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.