这是示例杰森数据。
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/