我有以下资料框,
df = pd.DataFrame([['Coca-Cola','Coca-Cola Ltd Co'], ['BMW','Company BMW Ltd'], ['Nike','Adidas Ltd and Co.']], columns=['Brand','Company Name'])
我需要根据“品牌”和“公司名称”列中的相同措辞来协调“状态”列:
Brand Company Name
Coca-Cola Coca-Cola Ltd Co
BMW Company BMW Ltd
Nike Adidas Ltd and Co.
理想情况下,我希望我的“状态”列将“相同”回传到相同的品牌和公司名称,将“不”回传到不同的,如下所示:
Brand Company Name Status
Coca-Cola Coca-Cola same
BMW Company BMW Ltd same
Nike Nike Ltd and Co. not
我目前的方法是有效的,但并非适用于所有人,因为某些公司名称介于两者之间或不同(具有完整的公司名称)
my_list=[]
for brands,names in zip(df.Brand,df["Company Name"]):
if brands==names:
my_list.append('same')
else:
my_list.append('not')
请分享您对我如何根据两列中的相同措辞进行协调的建议。谢谢。
uj5u.com热心网友回复:
如果品牌名称不是多个词,我们可以简单地Company Name
在空白处拆分并查找成员资格:
df['Status'] = df.apply(lambda x: 'same' if x['Brand'] in x['Company Name'].split() else 'not', axis=1)
输出:
Brand Company Name Status
0 Coca-Cola Coca-Cola Ltd Co same
1 BMW Company BMW Ltd same
2 Nike Adidas Ltd and Co. not
uj5u.com热心网友回复:
您可以使用List comprehension
更好的时间。zip
将列合并为一并检查是否Brand
存在于Company Name
:
In [251]: df['Status'] = ['same' if x in y else 'not' for x,y in zip(df['Brand'], df['Company Name'].str.split())]
In [252]: df
Out[252]:
Brand Company Name Status
0 Coca-Cola Coca-Cola Ltd Co same
1 BMW Company BMW Ltd same
2 Nike Adidas Ltd and Co. not
时间:
In [261]: def f1():
...: df['Status'] = df.apply(lambda x: 'same' if x['Brand'] in x['Company Name'].split() else 'not', axis=1)
...:
In [259]: def f2():
...: df['Status'] = ['same' if x in y else 'not' for x,y in zip(df['Brand'], df['Company Name'].str.split())]
In [262]: %timeit f1() # @Manlai's solution
468 μs ± 15.2 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [263]: %timeit f2() # my solution
360 μs ± 6.67 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
0 评论