Reputation:
I have a list that contains integer values as follows
mylist = [2, 10, 5]
Now I want to find the elements in 'mylist' in a csv file shown below and return the 'item_code' attached to it.
No, item_code
1, nm111
2, nm121
3, nm131
4, nm141
I am currently doing it using csv as follows.
with open('item_codes.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
if row[0] in mylist:
However, I am interested in doing this in pandas as well. Please help me.
Upvotes: 1
Views: 3075
Reputation: 14689
If you put the csv data into a dataframe like this :
df = pd.read_csv('item_codes.csv')
print(df)
output:
No, item_code
1, nm111
2, nm121
3, nm131
4, nm141
You could do the following:
df[df["No"].isin([2, 10, 5])]["item_code"].tolist()
which will give you a list of all the item_code
values in the same row as the integers from the list [2, 10, 5]
As suggested by @jezrael in the comments below we can also use df.loc
.
Explanation: Since df["No"].isin([2, 10, 5])
returns an array of booleans, we can use this array as a mask to select the rows and get the same results as follows:
df.loc[df["No"].isin([2, 10, 5]),"item_code"].tolist()
Upvotes: 4