【问题标题】:How can I check if a column in Pandas has a string with different case choices?如何检查 Pandas 中的列是否具有不同大小写选择的字符串?
【发布时间】:2020-07-29 06:22:43
【问题描述】:
【问题讨论】:
标签:
python
pandas
string
dataframe
【解决方案1】:
import pandas as pd
# test data
data = {'Country': ['PORTUGAL', 'ENGLAND', 'FRANCE', 'GERMANY', 'Portugal', 'SPAIN', 'SPAIN', 'portugal', 'ITALY', 'NETHERLANDS', 'PORTUGAL', 'ITALY', 'RUSSIA']}
# setup dataframe
df = pd.DataFrame(data)
# cast Country to lowercase
df['Country'] = df['Country'].str.lower()
# search for desired string with contains
portugal = df[df['Country'].str.contains('portugal')]
# display(portugal)
Country
0 portugal
4 portugal
7 portugal
10 portugal
【解决方案2】:
你可以传case=False
sub = df[df['Country'].str.contains('portugal',case=False)]
sub
Out[48]:
Country
0 PORTUGAL
4 Portugal
7 portugal
10 PORTUGAL
【解决方案3】:
@Trenton McKinney 和@YOBEN_S 都可以。不过,另一种 pythonic 方式是请使用?aiLmsux: regex flags。在这种情况下,暗示不区分大小写的标志 i。只要拼写正确,葡萄牙语的输入方式无关紧要。
df[df.Country.str.contains('(?i:Portugal)')]
Country
0 PORTUGAL
4 Portugal
7 portugal
10 PORTUGAL
【解决方案4】:
您可以创建嵌套的 if 语句来检查是否区分大小写。
由于默认 pandas 区分大小写,因此如果您搜索“PORTUGAL”而不是“portugal”,您可以获得想要的行为。