Prev: The 'DataFrame' object | Next: Modifying Columns in DataFrame
- 1) By column
- 2) By row (.ix, .iloc, .loc)
- 3) By scalar values (.at, .iat)
First make sure that you run the code below so that df is properly constructed for the following examples to run smoothly
import pandas as pd
df = pd.read_csv("../../data/sampledata.csv",sep=',',skiprows=3, header=0, index_col=0)
df
- a) Using the column names as indexes
- b) Using the position (integer index) of the columns
c = df['Country']
print(type(c))
c
c = df[['Country']]
print(type(c))
c
df.Country
# but not this: df.2007
df[['Country', '2007', '2015']]
df[[1]]
df[[1, 3, 5]]
df[[i for i in range(3)]]
- a) Using the .loc indexer for selection by label (see pandas docs on .loc)
- b) Using the .iloc indexer for selection by position (integer-based indexer) (see pandas docs on .iloc)
- c) Using the .ix indexer that is a handy combination of the above (see pandas docs on .ix)
# Note that a row is now constructed as a new DataFrame
gr = df.loc[['GRC']]
print(type(gr))
gr
gr = df.loc['GRC']
print(type(gr))
gr
df.loc[['GRC','ESP','PRT']]
df.loc['ESP':'GRC']
# You also get a new DataFrame
gr = df.iloc[[2]]
print(type(gr))
gr
esp = df.iloc[0]
print(type(esp))
esp
df.iloc[[2,4,6]]
df.iloc[2:5]
# .ix with row label
df.ix[['PRT']]
# .ix with list of row positions
df.ix[[0,2,4]]
# Slicing with labels
df.ix['ESP':'GRC']
# Slicing with positions
df.ix[3:5]
- a) Using the [ ] notation to provide column & row indexes
- b) Using the .at and .iat indexers
ita = df['Country']['ITA']
ita
# Also works without brackets for non-digit string indices
esp = df.Country.ESP
esp
d = df.at['FRA','Country']
d
d = df.at['FRA','2015']
d
d = df.iat[0,0]
d
d = df.iat[7,9]
d
x = 0
for i in range(len(df)):
for n in range(len(df.columns)):
if i==n:
print(df.iat[i,n])
m = df.ix['MLT']['Country']
m
m = df.ix['MLT'].Country
m
m = df.ix['MLT']['2010']
m
. Free learning material
. See full copyright and disclaimer notice