Home » Machine Learning » Pandas » Referencing Columns

Referencing Columns

To obtain the row indices in Pandas, we use the index property.

To obtain an entire column, we use the column name rather as if we were specifying an index in a 2D array.

This returns a Panda dataseries object, which represents a single column or data series.

import pandas as pd
from sklearn.datasets import load_iris
import numpy as np

iris = load_iris(as_frame=True)
df = pd.DataFrame(iris['data'])
df['species'] = np.choose(iris['target'], iris['target_names'])

print(list(df.index))

print(df['species'])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149]
0         setosa
1         setosa
2         setosa
3         setosa
4         setosa
         ...    
145    virginica
146    virginica
147    virginica
148    virginica
149    virginica
Name: species, Length: 150, dtype: object

This can also be used to create columns. Simply assign the column to a list, Numpy array or other suitable iterator.

Multiple Columns

You can specify multiple columns by giving a list of column names. The data type that’s returned is then another Pandas dataframe.

import pandas as pd
from sklearn.datasets import load_iris
import numpy as np

iris = load_iris(as_frame=True)
df = pd.DataFrame(iris['data'])
df['species'] = np.choose(iris['target'], iris['target_names'])

print(df[['petal length (cm)', 'species']])
 petal length (cm)    species
0                  1.4     setosa
1                  1.4     setosa
2                  1.3     setosa
3                  1.5     setosa
4                  1.4     setosa
..                 ...        ...
145                5.2  virginica
146                5.0  virginica
147                5.2  virginica
148                5.4  virginica
149                5.1  virginica

[150 rows x 2 columns]

Leave a Reply

Blog at WordPress.com.

%d