python - 在给定字符串中查找数据框的列值的pythonic方法
问题描述
我有一个像这样的熊猫数据框:
data={
'col1':['New Zealand', 'Gym', 'United States'],
'col2':['Republic of South Africa', 'Park', 'United States of America'],
}
df=pd.DataFrame(data)
print(df)
col1 col2
0 New Zealand Republic of South Africa
1 Gym Park
2 United States United States of America
我有一个句子可能包含来自数据框任何列的单词。我想获取给定句子中存在的列中的值以及它们所在的列。我见过一些类似的解决方案,但它们与给出的句子与列值相匹配,而不是相反。目前,我正在这样做:
def find_match(df,sentence):
"returns true/false depending on the matching value and column name where the value exists"
arr=[]
cols=[]
flag=False
for i,row in df.iterrows():
if row['col1'].lower() in sentence.lower():
arr.append(row['col1'])
cols.append('col1')
flag=True
elif row['col2'].lower() in sentence.lower():
arr.append(row['col2'])
cols.append('col2')
flag=True
return flag,arr,cols
sentence="I live in the United States"
find_match(df,sentence) # returns (True, ['United States'], ['col1'])
我想要一种更 Pythonic 的方式来做到这一点,因为它在相当大的数据帧上花费了大量时间,而且它对我来说似乎不是 Pythonic。
我不能使用 .isin() 因为它需要一个字符串列表并将列值与给定的整个句子匹配。我也尝试过执行以下操作,但它会引发错误:
df.loc[df['col1'].str.lower() in sentence] # throws error that df['col1'] should be a string
任何帮助将不胜感激。谢谢!
解决方案
我会做这样的事情:
def find_match(df,sentence):
ids = [(i,j) for j in df.columns for i,v in enumerate(df[j]) if v.lower() in sentence.lower()]
return len(ids)>0, [df[id[1]][id[0]] for id in ids], [id[1] for id in ids]
这使:
find_match(df, sentence = 'I regularly go to the gym in the United States of America')
(True,
['Gym', 'United States', 'United States of America'],
['col1', 'col1', 'col2'])
从我的感觉来看,这很像 pythonic,尽管可能有更优雅的方式来更多地使用 pandas 函数。
推荐阅读
- r - 如何下标/上标和斜体 x 轴标签?
- python - 为什么当我尝试使用默认构造函数实例化对象时,由于调用了参数化构造函数而出现错误?
- amazon-web-services - AWS S3 最终一致性:为什么存储桶列表返回一个键,但一个头请求无
- node.js - 如何使用 koa 框架托管 mp3 文件
- haskell - Haskell中作为类型变量的高级类型
- php - 删除附件页面上的页面标题
- matlab - 用于连接字符串的版本兼容方法
- python-3.x - 我想我在 jupyter notebook/python3 中进行故障排除时搞砸了我的文件目录
- python - 使用python对图像中的像素进行基于密度的异常值检测
- spring - Spring Security 和 i18n