gpt4 book ai didi

python - 如何将第一个字符串与列匹配并打印匹配?

转载 作者:行者123 更新时间:2023-11-28 21:40:44 25 4
gpt4 key购买 nike

我的数据框是

data = {
'company_name' : ['auckland suppliers', 'Octagone', 'SodaBottel','Shimla Mirch'],
'year' : [2000, 2001, 2003, 2004],
'desc' : [' auckland has some good reviews','Octagone','we shall update you','we have varities of shimla mirch'],
}

df = pd.DataFrame(data)

我试过这段代码

df['CompanyMatch'] = df ['company_name'] == df ['desc']

如果 company_name 列的第一个单词与 desc 列匹配,我想打印“匹配”。我很困惑将索引 [0] 放在哪里以便它以这种方式打印:

> company_name         desc                                 CompanyMatch
> auckland suppliers auckland has some good reviews Match
> Octagone Octagone Match
> SodaBottel we shall update you NA
> Shimla Mirch we have varities of shimla mirch Match

最佳答案

您可以使用 numpy.whereapply对于通过 in 检查另一列值,axis=1 用于按行处理:

import numpy as np

m = df.apply(lambda x: x['company_name'].lower() in x['desc'].lower(), axis=1)
df['CompanyMatch'] = np.where(m, 'Match', np.nan)
print (df)
company_name desc year CompanyMatch
0 auckland suppliers auckland has some good reviews 2000 nan
1 Octagone Octagone 2001 Match
2 SodaBottel we shall update you 2003 nan
3 Shimla Mirch we have varities of shimla mirch 2004 Match

编辑:

只比较第一个词:

m = df.apply(lambda x: x['company_name'].split()[0].lower() in x['desc'].lower(), axis=1)
df['CompanyMatch'] = np.where(m, 'Match', np.nan)
print (df)
company_name desc year CompanyMatch
0 auckland suppliers auckland has some good reviews 2000 Match
1 Octagone Octagone 2001 Match
2 SodaBottel we shall update you 2003 nan
3 Shimla Mirch we have varities of shimla mirch 2004 Match

关于python - 如何将第一个字符串与列匹配并打印匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45279922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com