Unieke Waarden
Gegevens worden vaak gedupliceerd in DataFrames. Bijvoorbeeld, in de countries
DataFrame heeft de 'continent'
kolom herhaalde vermeldingen. Er is een methode die een array van unieke waarden uit een specifieke DataFrame-kolom ophaalt.
import pandas as pd country_data = {'country' : ['Thailand', 'Philippines', 'Monaco', 'Malta', 'Sweden', 'Paraguay', 'Latvia'], 'continent' : ['Asia', 'Asia', 'Europe', 'Europe', 'Europe', 'South America', 'Europe'], 'capital':['Bangkok', 'Manila', 'Monaco', 'Valletta', 'Stockholm', 'Asuncion', 'Riga']} countries = pd.DataFrame(country_data) print(countries)
Nu zullen we de unique()
methode toepassen op de 'continent'
en 'country'
kolommen:
import pandas as pd country_data = {'country' : ['Thailand', 'Philippines', 'Monaco', 'Malta', 'Sweden', 'Paraguay', 'Latvia'], 'continent' : ['Asia', 'Asia', 'Europe', 'Europe', 'Europe', 'South America', 'Europe'], 'capital':['Bangkok', 'Manila', 'Monaco', 'Valletta', 'Stockholm', 'Asuncion', 'Riga']} countries = pd.DataFrame(country_data) unique_countries = countries['country'].unique() unique_continents = countries['continent'].unique() print(unique_countries) print(unique_continents)
Om het aantal unieke waarden in een specifieke kolom te tellen, kun je de nunique()
methode gebruiken:
import pandas as pd country_data = {'country' : ['Thailand', 'Philippines', 'Monaco', 'Malta', 'Sweden', 'Paraguay', 'Latvia'], 'continent' : ['Asia', 'Asia', 'Europe', 'Europe', 'Europe', 'South America', 'Europe'], 'capital':['Bangkok', 'Manila', 'Monaco', 'Valletta', 'Stockholm', 'Asuncion', 'Riga']} countries = pd.DataFrame(country_data) print(countries['continent'].nunique())
Taak
Swipe to start coding
Je hebt een DataFrame
genaamd audi_cars
.
- Identificeer alle verschillende waarden in de
'year'
kolom en sla het resultaat op in deunique_years
kolom. - Identificeer alle verschillende waarden in de
'fueltype'
kolom en sla het resultaat op in deunique_fueltype
variabele. - Bepaal het aantal unieke brandstoftypen en sla het resultaat op in de
count_unique_fueltypes
variabele.
Oplossing
Was alles duidelijk?
Bedankt voor je feedback!
Sectie 3. Hoofdstuk 15