pandas 不使用正则表达式通过字符串的一部分进行 loc 搜索
pandas loc search by part of a string not using regexp
import pandas as pd
data = {'name': ['HelloWorld', 'ByeWorld'],
'physics': [22, 33],
'chemistry': [44, 55]}
a = pd.DataFrame(data)
b = a.loc[a['name'] == 'Hello']
print(b)
此代码不会 return 任何行,但我想实现它 return 第一行,因为它包含“Hello”。有什么优雅的方案可以用 loc 命令解决这个问题吗?
你想要
b = a.loc[a['name'].str.contains('Hello')]
另外,如果您只查看字符串的开头,您可以使用
b = a.loc[a['name'].str.startswith('Hello')]
没有
b = a.loc[a['name'] == 'Hello']
这行代码只会 return 对于仅包含 Hello
的行为真
import pandas as pd
data = {'name': ['HelloWorld', 'ByeWorld'],
'physics': [22, 33],
'chemistry': [44, 55]}
a = pd.DataFrame(data)
b = a.loc[a['name'] == 'Hello']
print(b)
此代码不会 return 任何行,但我想实现它 return 第一行,因为它包含“Hello”。有什么优雅的方案可以用 loc 命令解决这个问题吗?
你想要
b = a.loc[a['name'].str.contains('Hello')]
另外,如果您只查看字符串的开头,您可以使用
b = a.loc[a['name'].str.startswith('Hello')]
没有
b = a.loc[a['name'] == 'Hello']
这行代码只会 return 对于仅包含 Hello