【问题标题】:pandas and numpy logic using 'isin' and 'str'使用“isin”和“str”的 pandas 和 numpy 逻辑
【发布时间】:2018-03-07 03:02:04
【问题描述】:

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

表格

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

如果 Field1=J 并且 Field2='JLP10' 的前 4 个字母,则返回 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 实际匹配时,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.. 任何想法为什么??

【问题讨论】:

    标签: python pandas numpy


    【解决方案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)))
    

    【讨论】:

    • 我们是最棒的!但是你能解释一下为什么是 0:5 吗?那不是意味着前 6 个字符吗??
    • @babz 不,这将是前 5 个字符 :-) 为什么我们也可以这样做 str[:5]
    • 真的很抱歉,但在某些情况下 Field2 是 'ABCD',末尾有 2 个空格。对于那些说“标识符中的字符无效”的情况,此脚本会返回错误
    • @babz 在你做这些条件之前Table.Field2=Table.Field2.str.strip(),链接这里pandas.pydata.org/pandas-docs/stable/generated/…
    • @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)))
    猜你喜欢
    • 2021-11-24
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多