T3J45 T3J45 - 2 months ago 24
Python Question

Print specific rows from dataframe using a condition

Be advised I'm doing this in a Function, and I've already referred a pretty good thread.

Here's the python function, the parameter passed is taken from user

def recommend(uid):
ds = pd.read_csv("pred_matrix-full_ubcf.csv")
records = ds.loc[ds['uid'] == uid]
for recom in records:
print recom


Data Format:

uid iid rat
344 1189 5
344 1500 5
344 814 5
736 217 3.3242361285
736 405 3.3238380154
736 866 3.323500531
331 1680 2
331 1665 2
331 36 1.999918585


Referred:
this1,
this2

Unable to get where I'm going wrong, I'm following this1 thread and yet unable to get it.

Answer Source

To iterate over your rows, use df.iterrows():

In [53]: records = df[df['uid'] == query]

In [54]: for index, row in records.iterrows():
    ...:     print(row['uid'], row['iid'], row['rat'])
    ...: 
344.0 1189.0 5.0
344.0 1500.0 5.0
344.0 814.0 5.0

There's two other possible ways to do select your data. You can use boolean indexing:

In [4]: query = 344

In [7]: df[df['uid'] == query]
Out[7]: 
   uid   iid  rat
0  344  1189  5.0
1  344  1500  5.0
2  344   814  5.0

You can also use DataFrame.query function:

In [8]: df.query('uid == %d' %query)
Out[8]: 
   uid   iid  rat
0  344  1189  5.0
1  344  1500  5.0
2  344   814  5.0