1

我设法完成了基本的决策逻辑,但具有讽刺意味的是,我在一些非常基本的事情上苦苦挣扎。我的代码有 80% 的情况被捕获,但剩下的 20% 需要帮助。甚至不确定这是否称为分支或仅仅是决策树,但它是初学者的东西。

我的数据的小样本:

import pandas as pd
import numpy as np
df = pd.DataFrame({
    'Part ID' : [ 'Power Cord', 'Cat5 cable', 'Laptop', 'Hard Disk', 'Laptop Case', 'USB drive'],
    'Part Serial Number' : [111222, 999444, 888333, 141417, np.NaN, 222666], 
    'Mother s/n': [100111, 200112, 888333, 888333, 888333, np.NaN],
    })
df['Part Serial Number'] = df['Part Serial Number'].astype('Int64')
df['Mother s/n'] = df['Mother s/n'].astype('Int64')
df

这是我的代码:

df['Is mother s/n known?'] = np.where(df['Mother s/n'].isin(df['Part Serial Number']), 'Yes', 'No')
df

它给出以下输出: 在此处输入图像描述

正如您在图像中看到的,某些结果应该不同。请问如何用 Pandas 分支我的代码来实现它?

4

1 回答 1

2

您可以使用select在多个条件之间进行选择(而不仅仅是在两个条件之间where):

import pandas as pd
import numpy as np
df = pd.DataFrame({
    'Part ID' : [ 'Power Cord', 'Cat5 cable', 'Laptop', 'Hard Disk', 'Laptop Case', 'USB drive'],
    'Part Serial Number' : [111222, 999444, 888333, 141417, np.NaN, 222666], 
    'Mother s/n': [100111, 200112, 888333, 888333, 888333, np.NaN],
    })
df['Part Serial Number'] = df['Part Serial Number'].astype('Int64')
df['Mother s/n'] = df['Mother s/n'].astype('Int64')

conditions = [df['Mother s/n'].eq(df['Part Serial Number']).fillna(False).astype(bool),
              df['Mother s/n'].fillna(-1).isin(df['Part Serial Number']),
              df['Mother s/n'].isna()]
choices = ['Self', 'Yes', 'Mother s/n unknown']
df['Is mother s/n known?'] = np.select(conditions, choices, 'No')

结果:

       Part ID  Part Serial Number  Mother s/n Is mother s/n known?
0   Power Cord              111222      100111                   No
1   Cat5 cable              999444      200112                   No
2       Laptop              888333      888333                 Self
3    Hard Disk              141417      888333                  Yes
4  Laptop Case                <NA>      888333                  Yes
5    USB drive              222666        <NA>   Mother s/n unknown
于 2021-02-13T12:31:14.383 回答