0
点赞
收藏
分享

微信扫一扫

python pandas query loc查找行 条件查询 筛选行 字符串 列表

list_t = ['aa', 'bb', 'cc']
df_t = pd.DataFrame(np.arange(5*3).reshape(-1, 3))  # -1表示自动计算, 不可不填
df_t.columns = ['col' + str(i) for i in range(3)]
df_t.iloc[:3, 0] = list_t
str_t = ""
for i, j in enumerate(list_t):
    j = repr(str(j))  # repr相当于前后加上单引号, 后面构造((查询表达式)字符串)时就不用加了
    if i <= len(list_t)-2:
        str_t += "(col0 == " + j + ") or \ \n"
    else:
        str_t += "(col0 == " + j + ")"
print(str_t)

# df_t.query(str_t)  # 失败 不可使用字符串代替表达式 即使...

print(
    df_t.query('''
        (col0 == 'aa') or \
        (col0 == 'bb') or \
        (col0 == 'cc')
    ''')
)  # query用于条件查询(行)

print(
    df_t.eval('''
        (col0 == 'aa') or \
        (col0 == 'bb') or \
        (col0 == 'cc')
    ''')
)  # eval返回运算结果, 用于执行运算表达式, 在pandas中用于列运算和赋值

print(
    df_t.query('''
        col0.isin(@list_t)
    ''')
)

print(
    df_t.loc[
        df_t['col0'].isin(list_t)
    ]
)

python pandas query loc查找行 条件查询 筛选行 字符串 列表_python pandas query

python pandas query loc查找行 条件查询 筛选行 字符串 列表_python pandas query_02

举报

相关推荐

0 条评论