Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用';isin';和';str';_Python_Pandas_Numpy - Fatal编程技术网

Python 使用';isin';和';str';

Python 使用';isin';和';str';,python,pandas,numpy,Python,Pandas,Numpy,尝试创建返回3、2或1的查询 桌子 如果Field1=J和Field2='JLP10'的前4个字母,则返回3,否则如果Field1=J,则返回2,否则返回1。 所以ID1应该返回3,ID2应该返回2,ID3应该返回1 我尝试了以下方法: Table=Table.assign(Field3=np.where(((Table.Field1=='J')&(Table.Field2.astype(str).str[0:4].isin(['JLP10', 'JLP15']))),3, np.whe

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

桌子

如果Field1=J和Field2='JLP10'的前4个字母,则返回3,否则如果Field1=J,则返回2,否则返回1。 所以ID1应该返回3,ID2应该返回2,ID3应该返回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实际匹配时,ID1得到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。。你知道为什么吗?

的“')”是错误的:-),而对于
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)))

你是最棒的!但是你能解释为什么是0:5吗?这不是意味着前6个字符吗?@babz不,这将是前5个字符:-)这就是为什么我们也可以做
str[:5]
我真的很抱歉,但是有些情况下,字段2是'ABCD',结尾有两个空格。在执行这些条件之前,此脚本返回一个错误,即@babz中的“标识符中的字符无效”@babz
Table.Field2=Table.Field2.str.strip()
,在这里链接@babz让我们尝试
str.startswith
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))
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)))