我有一个使用内置函数“ isin”在熊猫数据框中查找值的函数。问题是我想使此函数不区分大小写。我可以将每个列解析为一个序列并使用“ str.contains”,但是我觉得它有点难看。你知道一个好方法吗?
以下是返回给定世界的索引和col的函数:
def find_pos(self, titres):
bool_table = self.document.isin(titres)
for i in range(bool_table.shape[0]):
for j in range(bool_table.shape[1]):
boolean = bool_table.iloc[i][j]
if boolean:
return i, j
print(titres, " not found in csv", file=sys.stderr)
return -1, -1
一种可行的解决方案是使用lambda:
bool_table = self.document.apply(lambda x: x.astype(str).str.lower()).isin([x.lower() for x in titres])
由于我是python的新手,也许这不是执行此操作的最佳方法?
答案 0 :(得分:1)
另一种方法是首先找到匹配的列,然后找到行索引。 使用正则表达式进行不区分大小写的匹配。
一种示例方法是
def find_pos(search):
pattern = '(?i)' + search
# search in each column
for column in df:
df2 = df[df[column].str.contains(pattern, regex=True)]
if not df2.empty:
# find row index and column index
return (df2.index[0], df2.columns.get_loc(column))
idx = find_pos('to')
print(idx)
我尝试了以下示例数据
import pandas as pd
df = pd.DataFrame(columns = ['Name', 'Location'])
df.loc[len(df)] = ['Mathew', 'Houston']
df.loc[len(df)] = ['Tony', 'New York']
df.loc[len(df)] = ['Jerom', 'Los Angeles']
df.loc[len(df)] = ['Aby', 'Dallas']
df.loc[len(df)] = ['Elma', 'Memphis']
df.loc[len(df)] = ['Zack', 'Chicago']
df.loc[len(df)] = ['Lisa', 'New Orleans']
df.loc[len(df)] = ['Nita', 'Las Vegas']