根据另一列填充NaN值

时间:2020-10-08 21:37:58

标签: python dataframe nan fillna

我有这个pd.DataFrame:

test4 = pd.DataFrame({'condition': ['good', np.nan, np.nan, 'excellent', 'good', np.nan], 
                      'odometer': [np.nan, 35000, 20000, 100000, 500000, 50]})

输出:

condition   odometer
0   good    NaN
1   NaN 35000.0
2   NaN 20000.0
3   excellent   100000.0
4   good    500000.0
5   NaN 50.0

我无法使用“里程表”列中的值来填充“条件”列中的NaN值。条件将是:

odometer <=30000, then condition = 'good'
odometer > 30000 & odometer <=150000, then value = 'excellent'
odometer > 150000 & odometer <=10000000, then value = 'good'

最后应该看起来像这样:

condition   odometer
0   good    NaN
1   excellent   35000.0
2   good    20000.0
3   excellent   100000.0
4   good    500000.0
5   good    50.0

我尝试了其他方法,但是没有用。例如:

def f(change):
    if change['condition'] == np.nan:
        condition = change['odometer']
        value = change['condition']
        if   condition <=30000 value = 'good'
        elif condition > 30000 & condition <=150000 value = 'excellent'
        elif condition > 150000 & condition <=10000000 value = 'good'
        return value
    return change['condition']

test4['condition'] = test4.apply(f)

我在做什么错?有办法使它起作用吗?谢谢。

1 个答案:

答案 0 :(得分:0)

无论如何,我找到了答案,以防将来对任何人有帮助:

[id^=pin-draft-title-]