Python 如何计算两个相似列之间的索引交点?
我有以下清单:Python 如何计算两个相似列之间的索引交点?,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有以下清单: new_pets = ['Bobcats', 'dog', 'cat', 'turtle', 'monkey', 'goat', 'ferret', 'pig', 'Chipmunks', 'Capybaras', 'Ducks'] 以及以下数据帧: In: df 0 Cats 1 Lizard 2 Dog 3 Baby Ferrets 4 Pig 5 Armadillo 如何将出现在df(*)中的new\u pets元素放入新列中 从文档中,我注意
new_pets = ['Bobcats', 'dog', 'cat', 'turtle', 'monkey', 'goat', 'ferret', 'pig', 'Chipmunks', 'Capybaras', 'Ducks']
以及以下数据帧:
In: df
0 Cats
1 Lizard
2 Dog
3 Baby Ferrets
4 Pig
5 Armadillo
如何将出现在df
(*)中的new\u pets
元素放入新列中
从文档中,我注意到这可以用完成,因此我尝试了以下方法:
result = df[df['pets'].str.contains(x, case = False) for x in new_pets]
然而,我不确定这是否可能。例如,由于
雪貂
与雪貂
相似,是否可以将小雪貂
与雪貂
匹配?。对于该约束,我尝试使用case=False
,但没有得到预期的结果(*)。你知道如何在一个新的数据帧中检索这样的字符串吗?你可以先通过
(regex是
)连接值,然后通过lower
将所有值转换成小写-输出在连接的中。然后将列by中的所有值小写,并使用joined
调用,以检查bobcats
或dog
或dog
。。。在第列中:
print (df)
pets
0 Cats
1 Lizard
2 Dog
3 Baby Ferrets
4 Pig
5 Armadillo
joined = '|'.join(new_pets).lower()
df['new_col'] = df['pets'].str.lower().str.contains(joined)
print (df)
a new_col
0 Cats True
1 Lizard False
2 Dog True
3 Baby Ferrets True
4 Pig True
5 Armadillo False
谢谢你的帮助,你能解释一下吗?。。。我还检查是否可以使用“|”.join(新宠物).lower()
。但是,我不明白…非常感谢你,杰兹!这里的df.a.str
a
指的是什么?。。。另外,如果我的df
有更多的列,并且我只想集中精力匹配一个特定的列,该怎么办?。我是否应该这样做:df['new\u col']=df['sepcific\u col'].a.str.lower().str.contains(joined)
?对不起,这是列名。如果使用多个单词作为一个单词,请使用选择方式[]
:df['column 1']
,因此您需要df['new\u col']=df['sepecific\u col'].str.lower().str.contains(joined)
print (df)
pets
0 Cats
1 Lizard
2 Dog
3 Baby Ferrets
4 Pig
5 Armadillo
joined = '|'.join(new_pets).lower()
df['new_col'] = df['pets'].str.lower().str.contains(joined)
print (df)
a new_col
0 Cats True
1 Lizard False
2 Dog True
3 Baby Ferrets True
4 Pig True
5 Armadillo False