Uvod u Python Pandas

Prvi deo - DataFrame i Series

Pandas je Python biblioteka za rad sa tabelarnim podacima. To je popularan i zgodan alat za manipulaciju podacima. Posebno je korisno kada pripremate podatke za obuku modela mašinskog učenja.

Ako koristite Anacond-u, već imate unapred instaliranu Pandu. Ako ne, instalirajte ga sa pip:

pip install pandas

Kada smo instalirali Pandas biblioteku možemo je uvesti.

Kao i u radu sa drugim bibliotelama, sledimo konvenciju i koristimo pseudonim pd, umesto punog imena.

In [2]:
import pandas as pd

DataFrame i Series

Prvo ćemo istražiti dve najvažnije pandas strukture podataka:

  • Series (niz podataka)

  • DataFrame (okvir sa podacima)

Series

Series predstavlja jednodimenzionalni objekat koji može da skladišti vrednosti bilo kojeg tipa, slično koloni u tabeli. Svakoj vrednosti će biti dodeljen indeks od 0 do n, gdje n predstavlja za 1 manju vrednost od broja koji predstavlja veličinu od Series.

In [3]:
import pandas as pd

myS = pd.Series(['audi','bmw','honda','mazda','nissan'])

print(myS)
0      audi
1       bmw
2     honda
3     mazda
4    nissan
dtype: object

Vrednostima pristupamo preko indeksa na sledeći način.

In [3]:
myS[1]
Out[3]:
'bmw'
In [4]:
myS[0:3]
Out[4]:
0     audi
1      bmw
2    honda
dtype: object

Indekse možemo i sami kreirati.

In [5]:
myS.index = ['Red 1', 'Red 2', 'Red 3', 'Red 4','Red 5' ] 
myS
Out[5]:
Red 1      audi
Red 2       bmw
Red 3     honda
Red 4     mazda
Red 5    nissan
dtype: object
In [6]:
myS['Red 3']
Out[6]:
'honda'

Takođe možemo prilikom kreiranja objekata tipa Series da zadamo indekse.

In [7]:
import pandas as pd
marka_auta=['audi','bmw','honda','mazda','nissan']
indeksi=['Red 1', 'Red 2', 'Red 3', 'Red 4', 'Red 5']

myS1=pd.Series(marka_auta, index=indeksi)

# myS1=pd.Series(['audi','bmw','honda','mazda','nissan'], index=['Red 1', 'Red 2', 'Red 3', 'Red 4', 'Red 5'])
myS1
Out[7]:
Red 1      audi
Red 2       bmw
Red 3     honda
Red 4     mazda
Red 5    nissan
dtype: object

Ako imamo podatke sačuvane u Python rečniku, pomoću njih takođe možemo kreirati objekat tipa Series.

In [8]:
podaci={'Red 1':'audi', 'Red 2':'bmw', 'Red 3':'honda', 'Red 4':'mazda', 'Red 5':'nissan'}
myS2=pd.Series(podaci)
myS2
Out[8]:
Red 1      audi
Red 2       bmw
Red 3     honda
Red 4     mazda
Red 5    nissan
dtype: object
In [9]:
import pandas as pd

kalorija = {'dan1': 420, 'dan2': 380, 'dan3': 390}
# ključevi rečnika postaju indeksi
sCal = pd.Series(kalorija)

sCal
Out[9]:
dan1    420
dan2    380
dan3    390
dtype: int64
In [10]:
import pandas as pd

kalorija = {'dan1': 420, 'dan2': 380, 'dan3': 390}

sCal= pd.Series(kalorija, index = ['dan1', 'dan2'])

sCal
Out[10]:
dan1    420
dan2    380
dtype: int64

DataFrame

DataFrame predstavlja tabelarnu dvodimenzionalnu strukturu podataka sa kolonama i redovima sa potencijalno različitim tipovima podataka. Sastoji se od podataka, indeksa i kolona. Takođe se može posmatrati i kao grupa Series objekata koji dijele isti indeks.

Kreiraćemo sada jedan objekat tipa DataFrame.

In [11]:
import pandas as pd

data = {
    'gender':['Female','Male','Male','Male','Female'],
    'height':[174,189,185,195,165],
    'weight':[96,87,110,104,61],
    'indexBMI':[4,2,4,3,2]   
}

# učitava podatke u objekat DataFrame:
df_BMI = pd.DataFrame(data)

print(df_BMI) 
   gender  height  weight  indexBMI
0  Female     174      96         4
1    Male     189      87         2
2    Male     185     110         4
3    Male     195     104         3
4  Female     165      61         2
In [12]:
import pandas as pd

data = {
    'gender':['Female','Male','Male','Male','Female'],
    'height':[174,189,185,195,165],
    'weight':[96,87,110,104,61],
    'indexBMI':[4,2,4,3,2]   
}

# učitava podatke u objekat DataFrame:
df_BMI = pd.DataFrame(data, index=['person1','person2','person3','person4','person5'])

print(df_BMI) 
print(df_BMI.index) 
         gender  height  weight  indexBMI
person1  Female     174      96         4
person2    Male     189      87         2
person3    Male     185     110         4
person4    Male     195     104         3
person5  Female     165      61         2
Index(['person1', 'person2', 'person3', 'person4', 'person5'], dtype='object')

Učitavanje podataka iz CSV fajla

Jednostavan način za skladištenje velikih skupova podataka je korišćenje CSV datoteka (od engl. comma separated values). CSV datoteka je tekstualna datoteka u kojoj redovi odgovaraju redovima tabele, a podaci unutar istog reda su razdvojeni zarezima.

U sledećim primerima koristićemo CSV datoteku pod nazivom 'automobile_data.csv'.

Svi podaci za vežbe koje slede nalaze se u direktorijumu datasets jedan nivo iznad mesta gde se nalazi ova radna sveska. Dve tačke navedene u putanji koja je prosleđena read_csv tumače se kao direktorijum neposredno iznad trenutnog.

In [13]:
import pandas as pd

df1 = pd.read_csv('../datasets/automobile_data.csv')

#print(df1.to_string()) 
df1
Out[13]:
symboling normalized-losses make fuel-type aspiration num-of-doors body-style drive-wheels engine-location wheel-base ... engine-size fuel-system bore stroke compression-ratio horsepower peak-rpm city-mpg highway-mpg price
0 3 ? alfa-romero gas std two convertible rwd front 88.6 ... 130 mpfi 3.47 2.68 9.0 111 5000 21 27 13495
1 3 ? alfa-romero gas std two convertible rwd front 88.6 ... 130 mpfi 3.47 2.68 9.0 111 5000 21 27 16500
2 1 ? alfa-romero gas std two hatchback rwd front 94.5 ... 152 mpfi 2.68 3.47 9.0 154 5000 19 26 16500
3 2 164 audi gas std four sedan fwd front 99.8 ... 109 mpfi 3.19 3.4 10.0 102 5500 24 30 13950
4 2 164 audi gas std four sedan 4wd front 99.4 ... 136 mpfi 3.19 3.4 8.0 115 5500 18 22 17450
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
200 -1 95 volvo gas std four sedan rwd front 109.1 ... 141 mpfi 3.78 3.15 9.5 114 5400 23 28 16845
201 -1 95 volvo gas turbo four sedan rwd front 109.1 ... 141 mpfi 3.78 3.15 8.7 160 5300 19 25 19045
202 -1 95 volvo gas std four sedan rwd front 109.1 ... 173 mpfi 3.58 2.87 8.8 134 5500 18 23 21485
203 -1 95 volvo diesel turbo four sedan rwd front 109.1 ... 145 idi 3.01 3.4 23.0 106 4800 26 27 22470
204 -1 95 volvo gas turbo four sedan rwd front 109.1 ... 141 mpfi 3.78 3.15 9.5 114 5400 19 25 22625

205 rows × 26 columns

head i tail metode

  • head - podrazumevano vraća prvih 5 redova DataFrame-a

  • tail - podrazumevano vraća poslednjih 5 redova

In [14]:
df1.head()
Out[14]:
symboling normalized-losses make fuel-type aspiration num-of-doors body-style drive-wheels engine-location wheel-base ... engine-size fuel-system bore stroke compression-ratio horsepower peak-rpm city-mpg highway-mpg price
0 3 ? alfa-romero gas std two convertible rwd front 88.6 ... 130 mpfi 3.47 2.68 9.0 111 5000 21 27 13495
1 3 ? alfa-romero gas std two convertible rwd front 88.6 ... 130 mpfi 3.47 2.68 9.0 111 5000 21 27 16500
2 1 ? alfa-romero gas std two hatchback rwd front 94.5 ... 152 mpfi 2.68 3.47 9.0 154 5000 19 26 16500
3 2 164 audi gas std four sedan fwd front 99.8 ... 109 mpfi 3.19 3.4 10.0 102 5500 24 30 13950
4 2 164 audi gas std four sedan 4wd front 99.4 ... 136 mpfi 3.19 3.4 8.0 115 5500 18 22 17450

5 rows × 26 columns

In [15]:
df1.head(7)
Out[15]:
symboling normalized-losses make fuel-type aspiration num-of-doors body-style drive-wheels engine-location wheel-base ... engine-size fuel-system bore stroke compression-ratio horsepower peak-rpm city-mpg highway-mpg price
0 3 ? alfa-romero gas std two convertible rwd front 88.6 ... 130 mpfi 3.47 2.68 9.0 111 5000 21 27 13495
1 3 ? alfa-romero gas std two convertible rwd front 88.6 ... 130 mpfi 3.47 2.68 9.0 111 5000 21 27 16500
2 1 ? alfa-romero gas std two hatchback rwd front 94.5 ... 152 mpfi 2.68 3.47 9.0 154 5000 19 26 16500
3 2 164 audi gas std four sedan fwd front 99.8 ... 109 mpfi 3.19 3.4 10.0 102 5500 24 30 13950
4 2 164 audi gas std four sedan 4wd front 99.4 ... 136 mpfi 3.19 3.4 8.0 115 5500 18 22 17450
5 2 ? audi gas std two sedan fwd front 99.8 ... 136 mpfi 3.19 3.4 8.5 110 5500 19 25 15250
6 1 158 audi gas std four sedan fwd front 105.8 ... 136 mpfi 3.19 3.4 8.5 110 5500 19 25 17710

7 rows × 26 columns

In [16]:
df1.tail(3)
Out[16]:
symboling normalized-losses make fuel-type aspiration num-of-doors body-style drive-wheels engine-location wheel-base ... engine-size fuel-system bore stroke compression-ratio horsepower peak-rpm city-mpg highway-mpg price
202 -1 95 volvo gas std four sedan rwd front 109.1 ... 173 mpfi 3.58 2.87 8.8 134 5500 18 23 21485
203 -1 95 volvo diesel turbo four sedan rwd front 109.1 ... 145 idi 3.01 3.4 23.0 106 4800 26 27 22470
204 -1 95 volvo gas turbo four sedan rwd front 109.1 ... 141 mpfi 3.78 3.15 9.5 114 5400 19 25 22625

3 rows × 26 columns

Funkcija type

Upotrebom funkcije type možemo proveriti da li je objekat dfBMI zaista DataFrame

In [17]:
type(df1)
Out[17]:
pandas.core.frame.DataFrame

Selektovanje jedne kolone iz DataFrame-a - Series

Da biste izabrali jednu kolonu iz DataFrame-a, prosledite ime jedne od kolona operatoru zagrada, []. Vraćeni objekat će biti Series (niz podataka). Metode head i tail kod Series funkcionišu isto kao i kod DataFrames-a.

In [18]:
marka = df1['make']
marka.head()
Out[18]:
0    alfa-romero
1    alfa-romero
2    alfa-romero
3           audi
4           audi
Name: make, dtype: object
In [19]:
marka.tail(3)
Out[19]:
202    volvo
203    volvo
204    volvo
Name: make, dtype: object

Vizualizacija tabelarno predstavljenih podataka

Primer: Prikazati indexBMI iz date tabele grafikonom tako da imena osoba budu na horizontalnoj osi.

In [20]:
import pandas as pd 
import matplotlib.pyplot as plt

data = {
    'gender':['Female','Male','Male','Male','Female'],
    'height':[174,189,185,195,165],
    'weight':[96,87,110,104,61],
    'indexBMI':[4,2,4,3,2]   
}

# učitava podatke u objekat DataFrame:
df_BMI = pd.DataFrame(data, index=['person1','person2','person3','person4','person5'])


plt.bar(df_BMI.index, df_BMI['indexBMI'])
plt.title('BMI index')
plt.show()

Vežba 1

  1. Učitati fajl weather.csv
  2. "Zavirite" u podatke - head(), tail()
In [ ]:
 
In [ ]:
 
In [ ]:
 

Vežba 2

Selektujte kolonu temperature, podatke iz navedene kolone dodelite promenljivoj sa imenom temp. Prikažite prvih 10 vrednosti iz pomenute kolone.

In [ ]:
 

Vežba 3

Odredi tip objekta temp.

In [ ]:
 

Vežba 4

Izaberite poslednja 2 reda df_weather DataFrame-a i dodelite ga promenljivoj df_last_2. Odredi tip objekta df_last_2.

In [ ]:
 
In [ ]:
 

Vežba 5

Prikazati linijskim dijagramom prvih deset vrednosti iz kolone temperature.

In [ ]:
 

Učitavanje podataka sa udaljenih resursa

In [21]:
import pandas as pd
film = pd.read_csv("https://raw.githubusercontent.com/tiki-paunovic/PyLadies_meetup/main/Day_3/IMDB-Movie-Data.csv")
film.head()
Out[21]:
Rank Title Genre Description Director Actors Year Runtime (Minutes) Rating Votes Revenue (Millions) Metascore
0 1 Guardians of the Galaxy Action,Adventure,Sci-Fi A group of intergalactic criminals are forced ... James Gunn Chris Pratt, Vin Diesel, Bradley Cooper, Zoe S... 2014 121 8.1 757074 333.13 76.0
1 2 Prometheus Adventure,Mystery,Sci-Fi Following clues to the origin of mankind, a te... Ridley Scott Noomi Rapace, Logan Marshall-Green, Michael Fa... 2012 124 7.0 485820 126.46 65.0
2 3 Split Horror,Thriller Three girls are kidnapped by a man with a diag... M. Night Shyamalan James McAvoy, Anya Taylor-Joy, Haley Lu Richar... 2016 117 7.3 157606 138.12 62.0
3 4 Sing Animation,Comedy,Family In a city of humanoid animals, a hustling thea... Christophe Lourdelet Matthew McConaughey,Reese Witherspoon, Seth Ma... 2016 108 7.2 60545 270.32 59.0
4 5 Suicide Squad Action,Adventure,Fantasy A secret government agency recruits some of th... David Ayer Will Smith, Jared Leto, Margot Robbie, Viola D... 2016 123 6.2 393727 325.02 40.0

Pomoću naredbe read_html može se pročitati i tabela direktno iz HTML koda neke veb stranice.

In [22]:
US = pd.read_html("https://simple.wikipedia.org/wiki/List_of_U.S._states", header=0)[0]
US.head()
Out[22]:
Name &postal abbs. [1] Name &postal abbs. [1].1 Unnamed: 2 Cities Cities.1 Established[A] Population[B][3] Total area[4] Total area[4].1 Land area[4] Land area[4].1 Water area[4] Water area[4].1 Numberof Reps.
0 Name &postal abbs. [1] Name &postal abbs. [1] NaN Capital Largest (by population)[5] Established[A] Population[B][3] mi2 km2 mi2 km2 mi2 km2 Numberof Reps.
1 Alabama NaN AL Montgomery Birmingham Dec 14, 1819 4903185 52420 135767 50645 131171 1775 4597 7
2 Alaska NaN AK Juneau Anchorage Jan 3, 1959 731545 665384 1723337 570641 1477953 94743 245384 1
3 Arizona NaN AZ Phoenix Phoenix Feb 14, 1912 7278717 113990 295234 113594 294207 396 1026 9
4 Arkansas NaN AR Little Rock Little Rock Jun 15, 1836 3017804 53179 137732 52035 134771 1143 2961 4