我有一个这样的数据库(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
还尝试了第一个“如果”条件:
database['condition'][i] == np.nan
但是它不能正常工作...请帮助!
答案 0 :(得分:1)
您可以使用DataFrame.apply()通过函数生成新的条件列,然后将其替换。不确定列的类型。 df ['condition']。dtype会告诉您。看起来条件可能是字符串或对象,这可能会在您的逻辑中造成错误。如果是字符串列,则需要直接比较=='NaN'。如果是对象,则可以使用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)
答案 1 :(得分:1)
我为您提供了一个不错的班轮解决方案:
让我们创建一个示例数据框:
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