使用'isin'和'str'的大熊猫和numpy逻辑

问题描述 投票:0回答:1

尝试创建返回3或2或1的查询

ID   Field1   Field2
1    J        JLP10A
2    J        JLP22A
3    S        JLP25C

我想如果Field1 = J并且Field2的前4个字母='JLP10'然后返回3,否则如果Field1 = J则返回2否则返回1.因此ID 1应该返回3,ID 2应该返回2并且ID 3应该返回1。

我尝试过以下方法:

Table=Table.assign(Field3=np.where(((Table.Field1=='J')&(Table.Field2.astype(str).str[0:4].isin(['JLP10', 'JLP15']))),3, np.where(Table.Field1=='J'),2,1))))

对于ID1,这不会返回3 ..

当我删除[0:4]条件并使Field2实际匹配时,ID3获得3。

Table=Table.assign(Field3=np.where(((Table.Field1=='J')&(Table.Field2.isin(['JLP10A', 'JLP15']))),3, np.where(Table.Field1=='J'),2,1))))

所以代码没有正确读取0:4 ..任何想法为什么?

python pandas numpy
1个回答
1
投票

')'的数量是错的:-),而对于str[0:4]应该是str[0:5]

Table=Table.assign(Field3=np.where((Table.Field1=='J')&(Table.Field2.astype(str).str[0:5].isin(['JLP10', 'JLP15'])),3, np.where(Table.Field1=='J',2,1)))
Table
Out[124]: 
   ID Field1  Field2  Field3
0   1      J  JLP10A       3
1   2      J  JLP22A       2
2   3      S  JLP25C       1

#Table=Table.assign(Field3=np.where((Table.Field1=='J')&(Table.Field2.astype(str).str.startswith('JLP10','ABCD')),3, np.where(Table.Field1=='J',2,1)))
© www.soinside.com 2019 - 2024. All rights reserved.