繁体   English   中英

根据pandas中另一列的长度获取子字符串

[英]Getting a substring based on a length of another column in pandas

我有一个数据帧,

       plan_identifier wellthie_issuer_identifier
0  UNM99901AL0000001-DEN                   UNM99902
1  UNM99902AK0000001-DEN                   UNM99902
2  UNM99904AZ0000001-DEN                   UNM99904
3  UNM99905AR0000001-DEN                   UNM99905
4  UNM99906CA0000001-DEN                   UNM99906
5  UNM99908CO0000001-DEN                   UNM99909
6  UNM99909CT0000001-DEN                   UNM99909

我需要检查在获取wellthie_issuer_identifier的长度后是否考虑了plan_identifier的子字符串是否相等?

UNM99902长度为8,所以我的plan_identifier substring = UNM99901 现在这应该让我失误。

所以,只要不相等,我就应该得到假。

我的输出应该是: -

FALSE
TRUE
TRUE
TRUE
TRUE
FALSE
TRUE

我尝试了类似下面的事情 -

print(~(df['plan_identifier'].str[:(df['wellthie_issuer_identifier'].astype(str).str.len())] != df['wellthie_issuer_identifier']))

怎么做到这一点? 我们可以使用apply()吗?

numpy使用defchararray.find

s1=df.plan_identifier.values.astype(str)
s2=df.wellthie_issuer_identifier.values.astype(str)    
~np.core.defchararray.find(s1,s2).astype(bool)
 Out[64]: array([False,  True,  True,  True,  True, False,  True])

大熊猫中的字符串方法通常很慢。 您可以使用列表推导。 IIUC:

>>> [i in p for p,i in zip(df['plan_identifier'],df['wellthie_issuer_identifier'])]
[False, True, True, True, True, False, True]

# or assign to new column:

df['new_column'] = [i in p for p,i in zip(df['plan_identifier'],df['wellthie_issuer_identifier'])]
>>> df
         plan_identifier wellthie_issuer_identifier  new_column
0  UNM99901AL0000001-DEN                   UNM99902       False
1  UNM99902AK0000001-DEN                   UNM99902        True
2  UNM99904AZ0000001-DEN                   UNM99904        True
3  UNM99905AR0000001-DEN                   UNM99905        True
4  UNM99906CA0000001-DEN                   UNM99906        True
5  UNM99908CO0000001-DEN                   UNM99909       False
6  UNM99909CT0000001-DEN                   UNM99909        True

[编辑]在评论中,你说你只对字符串的开头感兴趣。 在这种情况下,您可以使用startswith代替:

[p.startswith(i) for p,i in zip(df['plan_identifier'],df['wellthie_issuer_identifier'])]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM