[英]Fill NaN values based on operators from another column
我有一個像這樣的數據庫(pd.DataFrame):
condition odometer
0 new NaN
1 bad 1100
2 excellent 110
3 NaN 200
4 NaN 2000
5 new 20
6 bad NaN
我想根據“里程表”的值填充“條件”的 NaN:
new: odometer >0 and <= 100
excellent: odometer >100 and <= 1000
bad: odometer >1000
我試圖這樣做,但它不起作用:
for i in range(len(database)):
if math.isnan(database['condition'][i]) == True:
odometer = database['odometer'][i]
if odometer > 0 & odometer <= 100: value = 'new'
elif odometer > 100 & odometer <= 1000: value = 'excellent'
elif odometer > 1000: value = 'bad'
database['condition'][i] = value
還嘗試制作第一個“if”條件:
database['condition'][i] == np.nan
但它也不起作用。
您可以使用 DataFrame.apply() 為您的 function 生成一個新的條件列,然后替換它。 不確定您的列是什么類型。 df['condition'].dtype 會告訴你。 看起來條件可以是字符串或 object,這可能會在您的邏輯中產生錯誤。 如果它是字符串列,則需要進行直接比較 == 'NaN'。 如果是 object,可以使用 np.nan 或 math.nan。 我在下面為每個案例提供了一個示例數據庫。 您可能還想測試里程表列的類型。
import numpy as np
import pandas as pd
# condition column as string
df = pd.DataFrame({'condition':['new','bad','excellent','NaN','NaN','new','bad'], 'odometer':np.array([np.nan, 1100, 110, 200, 2000, 20, np.nan], dtype=object)})
# condition column as object
# df = pd.DataFrame({'condition':np.array(['new','bad','excellent',np.nan,np.nan,'new','bad'], dtype=object), 'odometer':np.array([np.nan, 1100, 110, 200, 2000, 20, np.nan], dtype=object)})
def f(database):
if database['condition'] == 'NaN':
#if np.isnan(database['condition']):
odometer = database['odometer']
if odometer > 0 & odometer <= 100: value = 'new'
elif odometer > 100 & odometer <= 1000: value = 'excellent'
elif odometer > 1000: value = 'bad'
return value
return database['condition']
df['condition'] = df.apply(f, axis=1)
我有一個很好的單線解決方案給你:
讓我們創建一個示例 dataframe:
import pandas as pd
df = pd.DataFrame({'condition':['new','bad',None,None,None], 'odometer':[None,1100,50,500,2000]})
df
Out:
condition odometer
0 new NaN
1 bad 1100.0
2 None 50.0
3 None 500.0
4 None 2000.0
解決方案:
df.condition = df.condition.fillna(df.odometer.apply(lambda number: 'new' if number in range(101) else 'excellent' if number in range(101,1000) else 'bad'))
df
Out:
condition odometer
0 new NaN
1 bad 1100.0
2 new 50.0
3 excellent 500.0
4 bad 2000.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.