How can pandas search for a specific value in a row?
You can use the loc method to search for a specific value in a column. The loc method can take a logical expression as a condition and return the rows or columns that meet the condition.
Here is an example:
import pandas as pd
# 创建一个DataFrame
data = {'Name': ['Tom', 'Nick', 'John', 'Alex'],
'Age': [20, 25, 30, 35],
'Country': ['USA', 'Canada', 'UK', 'Australia']}
df = pd.DataFrame(data)
# 查找Age列中值为30的行的所有列
result = df.loc[df['Age'] == 30]
print(result)
The output result:
Name Age Country
2 John 30 UK
In the example above, we use df.loc[df[‘Age’] == 30] to find the rows in the Age column that have a value of 30, returning all columns that meet this condition.