![](/img/trans.png)
[英]return the column name from a table where a specific value in any row were found with python and pandas
[英]Filter a dataframe column for a keyword, return seperate column value (name) from the row where each keyword is found
如果有一個數據框,並且如果我在另一列中找到關鍵字,我想返回一列中的值。 所以下面如果我搜索apple
,我希望 output 是[a,b]
像這樣:
names words
a apple
b apple
c pear
我想要一個列表: [a,b]
我找到了使用str.contains
返回 boolean 值的方法,但不確定如何從同一行中的另一列中獲取值,這將為我命名。 一定有一個帖子我找不到如果有人可以指導我那里。
你可以做
list(df[df['words'].str.contains('apple')]['names'])
導致
['a', 'b']
df['words'].str.contains('apple')
為條件構建一個 boolean pandas 系列完整代碼:
import io
import pandas as pd
data = """
names words
a apple
b apple
c pear
"""
df = pd.read_csv(io.StringIO(data), sep='\s+')
lst = list(df[df['words'].str.contains('apple')]['names'])
>>>print(lst)
['a', 'b']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.