Getting/setting values using label-based indexing with loc

The .loc attribute of a DataFrame is used to select values using the labels of the entries. It can be used to retrieve single scalar values from a DataFrame (using singular string labels for both row and column), or multiple values from a DataFrame (using lists of row/column labels). Single and multiple indexing can also be used in combination to get multiple values from a single row or column. The following lines of code illustrate the retrieval of a single scalar value from the df DataFrame:

value = df3.loc[0,'new_col5']
print(value)

The output will be 7.0.

Single/multiple values can also be set using the .loc attribute and an equals sign:

df3.loc[[2,3,4],['new_col4','new_col5']] = 1
print(df3)

The output is as follows:

  col3 new_col1  new_col2  new_col3  new_col4  new_col5  new_col6
0    x                  0         5         5       7.0        10
1    y                  0         7         7       8.0        11
2    z                  0         9         1       1.0        12
3    a                  0        11         1       1.0        13
4    b                  0        13         1       1.0        14
5    c                  0        15        21       9.5        15
6    d                  0        17        23      10.5        16

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset