首页 > 解决方案 > 包含字符串和列表的 Pandas 列。如何仅隔离列表项?

问题描述

理想情况下,我尝试使用 np.where 根据列中的值是字符串还是列表来进行一些条件格式化。

这是我的样本数据集:

Out[101]: 

     CRM Opportunities Opportunity Name

3    [Sestina Bio, LLC , Austria , 1 EE]
4      EnviroPower Renewable: 2020-06-09
5       [Stimwave , Belgium, UK , 6 EEs]

还有更多,所以我不想将字符串传递给列表并通过该方法进行检查。理想情况下,我想隔离所有列表或字符串。

我感谢大家的帮助

标签: pythonpandasnumpy

解决方案


一个简单的字符串方法是使用str.startswithstr.endswith

l1 = df['CRM Opportunities Opportunity Name'].str.startswith('[')
l2 = df['CRM Opportunities Opportunity Name'].str.endswith(']')

df[(l1) & (l2)]

    CRM Opportunities Opportunity Name
0  [Sestina Bio, LLC , Austria , 1 EE]
2     [Stimwave , Belgium, UK , 6 EEs]

或者

np.where(l1 & l2, 'list','notalist')
array(['list', 'notalist', 'list'], dtype='<U8')

推荐阅读