Python 选择列中的行,其中一列中的值是另一列中值的子字符串
我在下面有一个数据框Python 选择列中的行,其中一列中的值是另一列中值的子字符串,python,pandas,dataframe,Python,Pandas,Dataframe,我在下面有一个数据框 >df = pd.DataFrame({'A':['apple','orange','grape','pear','banana'], \ 'B':['She likes apples', 'I hate oranges', 'This is a random sentence',\ 'This one too', 'Bananas are yellow']}) >pri
>df = pd.DataFrame({'A':['apple','orange','grape','pear','banana'], \
'B':['She likes apples', 'I hate oranges', 'This is a random sentence',\
'This one too', 'Bananas are yellow']})
>print(df)
A B
0 apple She likes apples
1 orange I hate oranges
2 grape This is a random sentence
3 pear This one too
4 banana Bananas are yellow
我正在尝试获取列B包含列A中的值的所有行
预期结果:
A B
0 apple She likes apples
1 orange I hate oranges
4 banana Bananas are yellow
我只能使用
>df[df['B'].str.contains(df.iloc[0,0])]
A B
0 apple She likes apples
如何获取所有这些行?与将两个值转换为lower和test contains by一起使用,并通过以下方式进行过滤:
或列出理解解决方案:
df = df[[a in b.lower() for a, b in zip(df.A, df.B)]]
df = df[[a in b.lower() for a, b in zip(df.A, df.B)]]
print (df)
A B
0 apple She likes apples
1 orange I hate oranges
4 banana Bananas are yellow