python - 如何使用 pandas 查找一行中的重复单词?

标签 python pandas

这是示例杰森数据。

id  opened_date      title       exposure state

1  06/11/2014 9:28 AM Device rebooted and crashed with error 0x024 critical open

2  06/11/2014 7:12 AM Not able to connect to WiFi                  High     open

3  07/23/2014 2:11 PM Sensor failed to recognize movement          Low open

4  07/07/2014 5:20 PM When sensor activated, device rebooted with error 0x024 critical closed

我想编写一个代码,输入为字符串,输出应指向 ID。

例如:

Input String = Sensor : Output = ID 3 and 4 has 'Sensor' word in it
Input String = 0x024  : Output = ID 1 and 4 has '0x024' in it.

我猜这将需要某种分组,但它适用于完整的数据集而不是字符串。 pandas 可以实现这一点吗?或者还有其他更好的解决方案来分析这个问题吗?

最佳答案

您可以使用loc用于根据创建的条件进行选择 str.contains使用参数 case=False。最后,如果您需要list,请使用 tolist :

li = ['Sensor','0x024']

for i in li:
    print (df.loc[df['title'].str.contains(i, case=False),'id'].tolist())
    [3, 4]
    [1, 4]

为了存储,您可以使用dict理解:

dfs = { i: df.loc[df['title'].str.contains(i, case=False),'id'].tolist() for i in li }

print (dfs['Sensor'])
[3, 4]
print (dfs['0x024'])
[1, 4]

如果您需要function,请尝试get_id:

def get_id(id):
    ids = df.loc[df['title'].str.contains(id, case=False),'id'].tolist()
    return "Input String = %s : Output = ID " % id + 
            " and ".join(str(x) for x in ids) + 
            " has '%s' in it." % id

print (get_id('Sensor'))
Input String = Sensor : Output = ID 3 and 4 has 'Sensor' in it.

print (get_id('0x024'))
Input String = 0x024 : Output = ID 1 and 4 has '0x024' in it.

按评论编辑:

现在更复杂了,因为使用逻辑and:

def get_multiple_id(ids):
    #split ids and crete list of boolean series containing each id
    ids1 = [df['title'].str.contains(x, case=False) for x in ids.split()]
    #http://stackoverflow.com/a/20528566/2901002
    cond = np.logical_and.reduce(ids1)

    ids = df.loc[cond,'id'].tolist()
    return "Input String = '%s' : Output = ID " % id +
           ' and '.join(str(x) for x in ids) +
           " has '%s' in it." % id

print (get_multiple_id('0x024 Sensor'))
Input String = '0x024 Sensor' : Output = ID 4 has '0x024 Sensor' in it.

如果使用逻辑or,那就更容易了,因为re中的or|,所以你可以使用0x024|传感器:

def get_multiple_id(id):
    ids = df.loc[df['title'].str.contains(id.replace(' ','|'), case=False),'id'].tolist()
    return "Input String = '%s' : Output = ID " % id +
            ' and '.join(str(x) for x in ids) +
            " has '%s' in it." % id

print (get_multiple_id('0x024 Sensor'))
Input String = '0x024 Sensor' : Output = ID 1 and 3 and 4 has '0x024 Sensor' in it.

关于python - 如何使用 pandas 查找一行中的重复单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37388648/

相关文章:

python - 具有无限数量参数的 Django urlpattern

javascript - 是否有基于浏览器的 Websocket 监听器实现?

python - 合并具有两个键列和重复键出现的数据帧(pandas)

python - 使用 selenium (python) 从条件下拉列表中选择一个选项

python - pytorch KLDivLoss损失为负

Python:递归生成器

python - Pandas 中的合并问题

python - 列表的列,将列表转换为字符串作为新列

python - pd.Grouper 与日期时间键结合另一个分组键似乎创建了错误的组数

python - 使用大型 (+15 gb) CSV 数据集和 Pandas/XGBoost