Reputation: 149
I have .csv file which looks like this:
id,product
1,car
1,phone
2,tv
I want to get all rows which match the certain condition e.g: If the id==1, and product value contains letter "a", print all matched rows (e.g '1,car' will be printed). I know this would be better to work with database but I need to work with csv file.
I tried with pandas:
import pandas as pd
df = pd.read_csv('products.csv')
for value_i in df.id:
for value_p in df.product:
if (value_i==2 and "a" in value_p):
print(value_i, value_p)
But I don't get a good result. If someone can give me a hint how to access values of a columns I would be thankful.
Upvotes: 1
Views: 3213
Reputation: 862441
You can use boolean indexing
and for check values in strings use str.contains
:
df1 = df[(df['id'] == 1) & (df['product'].str.contains('a'))]
print (df1)
id product
0 1 car
Detail:
print ((df['id'] == 1) & (df['product'].str.contains('a')))
0 True
1 False
2 False
dtype: bool
Upvotes: 3