Reputation: 1402
I have a python code where I am trying to read a csv file using pandas.
Once I have read the csv, the user is asked for input to enter the first name and I filter the records and show only the matching records.
Code :
# importing the module
import pandas as pd
# read specific columns of csv file using Pandas
df = pd.read_csv(r'D:\Extension\firefox_extension\claimant_record.csv', usecols = ['ClaimantFirstName','ClaimantLastName','Occupation'])
print(df)
required_df_firstName = input("Enter First Name of Claimant: ")
select_df = df[df['ClaimantFirstName'] == required_df_firstName]
print(select_df)
Issue : There are multiple records matching with first name so I want the user to be able to narrow down the result using first and last name and I am not able to properly write the AND condition.
What I have tried so far:
select_df = df[df['ClaimantFirstName'] == required_df_firstName]and df[df['ClaimantLastName'] == required_df_lastName]
Upvotes: 0
Views: 166
Reputation: 451
You can use boolean indexing to check more than one condition at once.
Here's how it would work:
import pandas as pd
# add sample data
data = {'ClaimantFirstName': ["Jane", "John"], "ClaimantLastName": ["Doe", "Doherty"]}
df = pd.DataFrame(data)
# filter by name
required_df_firstName, required_df_lastName = "John", "Doherty"
select_df = df.loc[(df['ClaimantFirstName'] == required_df_firstName) & (df['ClaimantLastName'] == required_df_lastName), ['ClaimantFirstName', 'ClaimantLastName']]
Upvotes: 1
Reputation: 323286
Check isin
#required_df_firstName = input("Enter First Name of Claimant: ")
#notice the input would be list type , like ['a','b']
select_df = df[df['ClaimantFirstName'].isin(required_df_firstName)]
Upvotes: 0