Lesson 2: Indexing, selecting and assigning
    1 / 11

    Lesson 2 of 6 · about 20 minutes

    Indexing, selecting and assigning

    Selecting columns

    Most of working with data is picking out the part you need. Every example in this lesson uses this small table of students:

    import pandas as pd
    
    df = pd.DataFrame({
        "name": ["Ava", "Ben", "Cleo", "Dan", "Eli"],
        "city": ["Leeds", "York", "Leeds", "Bath", "York"],
        "age": [12, 13, 12, 14, 13],
        "score": [88, 92, 79, 65, 95],
    })
    print(df)

    The output:

       name   city  age  score
    0   Ava  Leeds   12     88
    1   Ben   York   13     92
    2  Cleo  Leeds   12     79
    3   Dan   Bath   14     65
    4   Eli   York   13     95

    To get one column, put its name in square brackets. The result is a Series:

    import pandas as pd
    
    df = pd.DataFrame({
        "name": ["Ava", "Ben", "Cleo", "Dan", "Eli"],
        "score": [88, 92, 79, 65, 95],
    })
    print(df["score"])

    The output:

    0    88
    1    92
    2    79
    3    65
    4    95
    Name: score, dtype: int64

    df.score works too, as long as the column name has no spaces and does not clash with a pandas method name. Square brackets always work, so they are the safer habit.

    To get several columns, pass a list of names. Note the double brackets: the outer pair selects, the inner pair is the list. The result is a smaller DataFrame:

    import pandas as pd
    
    df = pd.DataFrame({
        "name": ["Ava", "Ben", "Cleo"],
        "city": ["Leeds", "York", "Leeds"],
        "score": [88, 92, 79],
    })
    print(df[["name", "score"]])

    The output:

       name  score
    0   Ava     88
    1   Ben     92
    2  Cleo     79