python - 使用条件打印数据框中的特定行

标签 python pandas dataframe

请注意我正在函数中执行此操作,并且我已经引用了一个非常好的线程。

这里是python函数,传递的参数取自用户

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

数据格式:

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

引用: this1 , this2

无法找到我出错的地方,我正在关注this1线程,但无法得到它。

最佳答案

要迭代行,请使用 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
<小时/>

还有另外两种可能的方法来选择数据。您可以使用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

您还可以使用DataFrame.query功能:

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

关于python - 使用条件打印数据框中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44984332/

相关文章:

python - 如何使用未知数组维度进行 numpy 组合切片和数组索引

python - 如何从 df 中删除特定年份

python - 如何在拆分字符串和数字之前避免包含字符串和数字的行?

r - 按组将均值列添加到原始数据中

python - 使用原始索引获取 Pandas 重复行数

python - Django - 包括应用程序网址

python - 水管破裂的原因

python - 如何在 AI 平台培训中将 pandas-gbq 与 BigQuery Storage API 结合使用?

python - 在 Python 中使用周期性正态分布 (von Mises) 提取时间特征

python - python 对给定键集的 csv 进行排序