Python - 如果两个条件匹配熊猫,则返回第三列值

时间:2021-05-26 01:26:11

标签: python pandas

我有这样的 Pandas DF:

Data

现在我需要得到 UTB1050_1PCS,如果条件匹配 Brother 和 _1PCS,UTB1050_2PCS 如果我的条件匹配 Brother 和 _2PCS。

非常感谢!

1 个答案:

答案 0 :(得分:1)

这是数据框

import pandas as pd

list1=['_1PCS','_2PCS']
list2=['UTB1050_1PCS','UTB1050_2PCS']
list3=['Brother','Brother']

df=pd.DataFrame({'Variation':list1,
                 'Internal Code-Variation':list2,
                 'Brand':list3})

print(df)

原始数据

  Variation Internal Code-Variation    Brand
0     _1PCS            UTB1050_1PCS  Brother
1     _2PCS            UTB1050_2PCS  Brother

使用 Pandas .loc 过滤的数据

import pandas as pd

list1=['_1PCS','_2PCS']
list2=['UTB1050_1PCS','UTB1050_2PCS']
list3=['Brother','Brother']

df=pd.DataFrame({'Variation':list1,
                 'Internal Code-Variation':list2,
                 'Brand':list3})

filtered = df.loc[(df['Brand']=='Brother') & (df['Variation']=='_2PCS')]

输出

 Variation Internal Code-Variation    Brand
1     _2PCS            UTB1050_2PCS  Brother

有很多方法可以解决这个问题,我还建议您查看 Indexing and Selecting