Home>
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
ids = [100,101,102]
for i in range (3):
    df = pd.read_csv ('users.csv')
    df = df.query ('ID' == ids [i])
If i write

and run the code,
ValueError: expr must be a string to be evaluated,<class'bool'>given
I wrote this code because I wanted to extract the one whose ID index is 100 or 101 or 102. What is wrong?

  • Answer # 1

    pandas.DataFrame.query — pandas 0.23.0 documentation

      

    DataFrame.query (expr, inplace = False, ** kwargs)
      expr: string
      The query string to evaluate.You can refer to variables in the environment by prefixing them with an ‘@’ character like @a + b.

    First of all, the query argument isstring (str).

    Since the CSV used for input is not included in the question text, preparing appropriate data is like this

    import pandas as pd
    data = {"user": ["Alice", "Bob", "Mike", "Kenji", "Tim"], "ids": [100, 101, 102, 103, 104]}
    df = pd.DataFrame.from_dict (data)
    print (df)
    "" "
        user ids
    0 Alice 100
    1 Bob 101
    2 Mike 102
    3 Kenji 103
    4 Tim 104
    "" "
    print (df.query ("ids == 100"))
    "" "
        user ids
    0 Alice 100
    "" "
      

    I wrote this code because I wanted to extract one with an ID index of 100 or 101 or 102. What is wrong?

    print (df.query ("ids == 100 or ids == 101 or ids == 102"))
    "" "
        user ids
    0 Alice 100
    1 Bob 101
    2 Mike 102
    "" "
    print (df.query ("100<= ids<= 102"))
    "" "
        user ids
    0 Alice 100
    1 Bob 101
    2 Mike 102
    "" "
    ids = [100, 101, 102]
    print (df [df ["ids"]. isin (ids)])
    "" "
        user ids
    0 Alice 100
    1 Bob 101
    2 Mike 102
    "" "
    Reference

    note.nkmk.me-query to extract pandas.DataFrame rows as a condition
    pandas.DataFrame.query — pandas 0.23.0 documentation

  • Answer # 2

    According to this site (https://note.nkmk.me/python-pandas-query/)
    '"ID"== ids [i]'
    It seems that the value (true, false) of'ID'== ids [i] is evaluated from the amateur eyes.

Related articles