Installatie op windows geeft fouten na : ipython --pylab
This application failed to start because it could not find or load the Qt platform plugin "windows"
Oplossen door
COPY the
Continuum\Anaconda3\Library\plugins\platforms
folder to
Continuum\Anaconda3
woensdag 29 maart 2017
maandag 13 maart 2017
Pandas
waarom Pandas
Pandas helps to carry out your entire data analysis workflow in Python without having to switch to a more domain specific language like RDataframe = pythonic analog of R's dataframe
Data-science met python gebruik dan PANDAS
dmv het manipuleren van python pandas dataframes kan
- exploration data-analysis
- data-wrangling
- datapreprocessing
- building models
- visualization
https://www.youtube.com/watch?v=8uK65aNfQ3I
Panda vs Numpy
Numpy: voor berekeningen met getallen. Vooral voor matrix en vector. Sci-kitPandas: voor gestructureerde data
import flat files
# Import pandas as pdimport pandas as pd
# Assign the filename: file
file = opa.csv'
# Read the file into a DataFrame: df
df = pd.read_csv(file)
#je kan ook een dataframe vullen via een python dictionary
Basisfuncties
# Dataframe is about rows and columns#geeft dimensies van rijen en kolommen
df.shape
bijv : rows, columns =df.shape
# View the head of the DataFrame
print(df.head())
# View de last records
df.tail()
indexing and slicing
# print rij 2 to 4df[2:5]
# print alle columns
df.columns
print(list(dfnew.columns))
# print content column
df.windspeed
of
df['windspeed']
# geeft type van column
type(df['windspeed']
#alleen paar kolumns
df[['event']['windspeed']]
Operations Pandas
# maximum,meandf['temperature']. max()
#geef statistics data
df.describe()
Select data in dataframe
# soort SQLwhere clause
df[df.temperature>=32]
# geef regel met max temperatur
df[df.temperature==df['temperature'].max()]
# geef alleen regels waar een kolomwaarde NIET in een lijst is
df_debet_tmp=df_debet[~df_debet.ID_FACTUURREGEL.isin(lst_debet_found)]
# geef alleen bepaalde columns in het resultaat
df['day'].[df.temperature==df['temperature'].max()]
a= df_credit[df_credit['C_FACTUUR']=='22501-05-1731-05-17JH04Jgd-Verblijf jeu']
Maak een subset
#geef columns van dataframeorders.columns
#maak een subset
orders_subset = Dataframe(orders, columns=['Row id', Order Id],
orders_subset.head()
Indexes
elke dataframe heeft een INTEGER index die loopt van 0 tm mx (bijv 5)bij df.index krijg je dan te zien start=0 en stop =6 < dus 1 lager dan de werkelijke 5
standaard zijn de indexen getallen van 0 tm 5 maar je kan de index ook veranderen. bijv naar dag
df.set_index(['day'] it returns a new dataframe als je wilt dat deze df zelf veranderd dan
df.set_index(['day', inplace=True
dan is het mogelijk
df.loc['1/4/2017']
df.reset_index(inplace=true)
Als index meerdere gelijke waarden bevat, dan toon hij deze bij selectie met loc
Group by (split apply combine)
# groeperen op cityg=df.groupby('city')
g is ad dataframegroupby objects. er worden 3 groupen gecreerd
index newyork bevat dataframe
index paris bevat dataframe
for city, city_df in g:
print(city)
print(city_df)
# benaderen spefiek dataframe
g.get_group('Paris') geeft dataframe met group
# geef per city de max values
g.max()
# split / apply/combine
split: in datagroupen per city
apply: som operations op alle groupen
combine: combine result in datafaframe
# Inline printen
%matplotlib inline
g.plot
Concatenate
je kan 2 of meerdere dataframes concateneren tot 1 dataframedf = pd.concat([india_weather],[us_weather])
de indexen worden dan overgenomen van de bestaande dataframes. Dus dan heb je 2x zelfde getallen. Wil je een nieuwe nummering van de indexen dan moet je
df = pd.concat([india_weather],[us_weather], ignore_index=True)
# additonal Index
df = pd.concat([india_weather],[us_weather],keys=["india","us" )
hij maakt nu een extra index aan india en us
df.loc["us"]
AXIS
standaard is bij de conatenate de axis is 0 (append as row_. Dat betekent dat de rijen van het ene dataframe geplakt worden bij het andere dataframe. handig als je 2 dataframes van verschillende steden met zelfde kenmerken onder elkaar wil plakken. maar als je 2 dataframes van de zelfde steden heb met verschillende kenmerken. Wil je ze niet onder elkaar maar dan wil je de kenmerken op 1 regel. Dit doe je door de AXIS op 1 te zetten.(Append as column)
df.concate([temp_df],[wind_df],axis=1)
er wordt gematched bij rowindex
wat gebeurt als order
Voorbeeld
df_credit_small =pd.DataFrame(df_credit['ID_FACTUURREGEL'])
# er wordt automatisch een Serieobject gemaakt bij 1 columnnaam door Python, daarom weer een dataframe van maken
df_lst_debet_found=pd.DataFrame(lst_debet_found,columns=['ID_FACTUURREGEL'])
df_credits_debets=pd.concat([df_credit_small,df_lst_debet_found] ,ignore_index=True)
#df_credits_debets=df_credit_small.append(pd.DataFrame(lst_debet_found,columns=['ID_FACTUURREGEL']),ignore_index=True)
creddeblist=df_credits_debets['ID_FACTUURREGEL'].tolist()
Merge
Gelijk aan SQL JOIN. dataframes kan je ook mergen. dan worden de column geappend en dit gebeurt op basis van de ON veldendf3=pd.merge(df1,df2, on="city")
Werkt als een INNER JOIN default
een OUTER join doe je via
df3=pd.merge(df1,df2, on="city", how="outer")
LEFT outer : how = "left"
indicator="true" : geeft aan waar de join vandaan komt
suffixes=('_left', '_right')
Pivot
pivot allows you to transform or reshape datamaak een nieuwe shape , wat wil je op je x-as als index en wat wil je als column
df.pivot(index='"data",columns="city")
df.pivot(index='"data",columns="city", values="humidity") geef alleen humidity
Pivot table
pivot table is used to summarize and aggregate data inside a dataframedf.pivot_table(index="city",columns="date", aggfunc="sum")
df.pivot_table(index=pd.grouper(freq='M', key='date'),columns='city') via frequentie wordt er een maand van de index gemaakt
Handling missing data(Nan)
https://www.youtube.com/watch?v=EaGbS7eWSs0als je datumvelden inleest in panda krijgen ze allemaal een string value. Als je dit wil veranderen dan inlezen met parse_dates
df=pd.read_csv("" weather_data.csv",parse_dates=["day"]
#zet day als index in de dataframe
df.set_index('day', inplace=True)
# interpolate to make a guess on missing values using interpolation
Replace all Nan values with a gues vallue
new_dfdf.fillna(0)
#different values for different columns, then use dictionary instead of value
new_df=df.fillna({ 'temperature':0,'windspeed':0,'event': 'no-event'})
#geef missing value de waarde van vorige
new_df=df.fillna(method="ffill")
# backward fill
new_df=df.fillna(method="bfill")
# Coping rows horizontally.
new_df=df.fillna(method="bfill", axis="columns")
Maar 1 x kopieren van waarde
new_df=df.fillna(method="ffill",limit=1)
How to make better guess with interpolate instead with fill
new_df=df.interpolate()new_df=df.interpolate(method="time")
drop rows with missing values
df.dropna()
df.dropna(how="all")
als je 2 valid values hebt dan niet droppen
df.dropna(thres=2)
Vul datum index aan en reindex
dt=pd.date_range("01-01-2017","01-11-2017")
idx =pd.DatetimeIndex(dt)
df=df.reindex(idx)
Iteratie dataframe
for index, row in df.iterrows():
....: print row['c1'], row['c2']
let op. als je alleen index of row doet krijg je andere dataypes
met index,row
for index,row in df.iterrows():
print(type(index))
print(type(row))
<class 'numpy.int64'>
<class 'pandas.core.series.Series'>
<class 'numpy.int64'>
<class 'pandas.core.series.Series'>
met alleen row of alleen index
for row in df.iterrows():
print(type(row))
<class 'tuple'>
<class 'tuple'>
for index in df.iterrows():
print(type(index))
<class 'tuple'>
<class 'tuple'>
Dus als je per rij van een PANDAS dataframe de values wil doorlopen gebruik dan de volgende constructie
szsql="insert into TESTFACTUUR VALUES ("
values=""
methode1
for index,row in df.iterrows():
for myrow in row:
values= values + "'" + str(myrow) + "'"
methode 2
for index,row in df.iterrows():
for t1 in df.iloc[index]:
values= values + "'" + str(t1) + "'"
Uitleg Dataframe en indexen
IndexVerwarring benaderen
df.ozone of
df ['Ozone']
standaard altijd index beginnend bij 0 maar je kan ook zefl een index maken. bijv index month
Selecteren rij kolom
Voor het selecteren van een rij kan je iloc of loc gebruikendf ['Ozone'].iloc[2] : los van de index pak de zoveelste rij
df ['Ozone'].loc["Pietj"] : zoek deze waarde op in index
voor het selecteren van een kolom kan je gewoon de kolomnaam pakken
print(df["Fourth"])
selecteren specifiek veld
Let’s say you have a DataFrame like this one A B C
0 1 2 3
1 4 5 6
2 7 8 9
And you want to access the value that is at index 0, in column ‘A’.Well, here are the various options that exist to get your value
1
back:# Using `iloc[]`
print(df.iloc[0][0])
# Using `loc[]`
print(df.loc[0]['A'])
# Using `at[]`
print(df.at[0,'A'])
# Using `iat[]`
print(df.iat[0,0])
# Using `get_value(index, column)`
print(df.get_value(0, 'A'))
Kolommen zoeken met hoogste waarde
df.loc[df.values.argmax(axis=0)]
joinen van dataframes
allerlei opties kan je meegeven bijv type join etc. Doe Shift + TAB voor uitleg in IPython. er zijn 2 methods om te joinenvia JOIN : dan moet je bij een dataframe specifieke indexkolomen opgeven
df1 = pd.DataFrame({
'col1': [1,2,3,4,5,6],
'cat': ['a','b','c','d','e','f']
}).set_index('cat')
df2 = pd.DataFrame({
'col2': [7,8,9,10,11,12],
'cat': ['a','b','c','d','e','f']
}).set_index('cat')
df1.join(df2)
col1 | col2 | |
---|---|---|
cat | ||
a | 1 | 7 |
b | 2 | 8 |
c | 3 | 9 |
d | 4 | 10 |
e | 5 | 11 |
f | 6 | 12 |
via MERGE
df1 = pd.DataFrame({
'col1': [1,2,3,4,5,6],
'cat': ['a','b','c','d','e','f']
})
df2 = pd.DataFrame({
'col2': [7,8,9,10,11,12],
'cat2': ['a','b','c','d','e','f']
})
via merge .
df1.merge(df2, left_on='cat', right_on='cat2')
Extraaatjesaanmaken Dataframe
df1 = pd.DataFrame({
'col1': [1,2,3,4,5,6],
'cat': ['a','b','c','d','e','f']
})
mapping_dict={1:2,3:2,np.nan:0)
of df2['col3']=df2.col1.map(mappng_dict)
importing Text files
import textfiles
# Open a file: file
file = open('opa.txt','r')
# Print it
print(file.read())
# Check whether file is closed
print(file.closed)
# Close file
file.close()
# Check whether file is closed
print(file.closed)
context manager
it is important to close an open file. a way to do this automaticaly is to use a context manager. Out of the context everything will be automatically closed.
you can bind a variable
file
by using a context manager construct:
with open('huck_finn.txt') as file:
with open('huck_finn.txt') as file:
print(file.read())
Numpy
- standard for storing numerical data -essential for other packages scikit-learn (machine learning)
vrijdag 3 maart 2017
matplotlib
With matplotlib, you can create a bunch of different plots in Python.
The most basic plot is the line plot. A general recipe is given here.
import matplotlib.pyplot as plt
plt.plot(x,y)
plt.show()
ticks/labels
# Scatter plot
plt.scatter(gdp_cap, life_exp)
# Previous customizations
plt.xscale('log')
plt.xlabel('GDP per Capita [in USD]')
plt.ylabel('Life Expectancy [in years]')
plt.title('World Development in 2007')
# Definition of tick_val and tick_lab
tick_val = [1000,10000,100000]
tick_lab = ['1k','10k','100k']
# Adapt the ticks on the x-axis
plt.xticks(tick_val,tick_lab)
# After customizing, display the plot
plt.show()
sizes
# Import numpy as np
import numpy as np
# Store pop as a numpy array: np_pop
np_pop=np.array(pop)
# Double np_pop
np_pop=np_pop*2
# Update: set s argument to np_pop
plt.scatter(gdp_cap, life_exp, s = np_pop)
# Previous customizations
plt.xscale('log')
plt.xlabel('GDP per Capita [in USD]')
plt.ylabel('Life Expectancy [in years]')
plt.title('World Development in 2007')
plt.xticks([1000, 10000, 100000],['1k', '10k', '100k'])
# Display the plot
plt.show()
NUMPY
Numpy is een numerical python list
speciale list tbv datascience
Hiermee kan je operaties uitvoeren op een hele lijst.
Numpy is a Python package to efficiently do data science. Learn to work with the Numpy array, a faster and more powerful alternative to the list
numpy
- standard for storing numerical data
-essential for other packages scikit-learn (machine learning)
# height and weight are available as a regular lists
# Import numpy
import numpy as np
# Calculate the BMI: bmi
np_height_m = np.array(height) * 0.0254
np_weight_kg = np.array(weight) * 0.453592
bmi = np_weight_kg / np_height_m ** 2
print(bmi)
# Create the light array
light=bmi<21
# Print out light
print(light)
# Print out BMIs of all baseball players whose BMI is below 21
print(bmi[light])
import numpy as np
# Convert positions and heights to numpy arrays: np_positions, np_heights
np_positions=np.array(positions)
np_heights=np.array(heights)
# Heights of the goalkeepers: gk_heights
gk_heights = np_heights[np_positions=='GK']
# Heights of the other players: other_heights
other_heights = np_heights[np_positions!='GK']
# Print out the median height of goalkeepers. Replace 'None'
print("Median height of goalkeepers: " + str(np.median(gk_heights)))
# Print out the median height of other players. Replace 'None'
print("Median height of other players: " + str(np.median(other_heights)))
Remember how you calculated the Body Mass Index for all baseball players? Numpy was able to perform all calculations element-wise. For 2D Numpy arrays this isn't any different! You can combine matrices with single numbers, with vectors, and with other matrices.
Execute the code below in the IPython shell and see if you understand:
speciale list tbv datascience
Hiermee kan je operaties uitvoeren op een hele lijst.
Numpy is a Python package to efficiently do data science. Learn to work with the Numpy array, a faster and more powerful alternative to the list
numpy
- standard for storing numerical data
-essential for other packages scikit-learn (machine learning)
calculatie element wise voorbeeld 1.
bijv converteer inch naar kg dmv van een vermenigvuldiging op een numpy arry# height and weight are available as a regular lists
# Import numpy
import numpy as np
# Calculate the BMI: bmi
np_height_m = np.array(height) * 0.0254
np_weight_kg = np.array(weight) * 0.453592
bmi = np_weight_kg / np_height_m ** 2
print(bmi)
# Create the light array
light=bmi<21
# Print out light
print(light)
# Print out BMIs of all baseball players whose BMI is below 21
print(bmi[light])
voorbeeld 2
# Import numpyimport numpy as np
# Convert positions and heights to numpy arrays: np_positions, np_heights
np_positions=np.array(positions)
np_heights=np.array(heights)
# Heights of the goalkeepers: gk_heights
gk_heights = np_heights[np_positions=='GK']
# Heights of the other players: other_heights
other_heights = np_heights[np_positions!='GK']
# Print out the median height of goalkeepers. Replace 'None'
print("Median height of goalkeepers: " + str(np.median(gk_heights)))
# Print out the median height of other players. Replace 'None'
print("Median height of other players: " + str(np.median(other_heights)))
Numpy matrix
Remember how you calculated the Body Mass Index for all baseball players? Numpy was able to perform all calculations element-wise. For 2D Numpy arrays this isn't any different! You can combine matrices with single numbers, with vectors, and with other matrices.
Execute the code below in the IPython shell and see if you understand:
import numpy as np
np_mat = np.array([[1, 2],
[3, 4],
[5, 6]])
np_mat * 2
np_mat + np.array([10, 10])
np_mat + np_mat
Abonneren op:
Posts (Atom)
Datums bepalen adhv begin en einddatum in Dataframe
Voorbeeld op losse velden ####################################################################### # import necessary packages from datetime...
-
value_counts geef per waarde het aantal voorkomens in een bepaalde df_iris.species.value_counts() versicolor 50 setosa 50 v...
-
import textfiles # Open a file: file file = open('opa.txt','r') # Print it print(file.read()) # Check whether file ...
-
scikit-learn, a standard library for machine learning in Python. It describes itself like this: Machine Learning in Python •Simple and...