Teil 1 :¶
Bereinigung und Vorbereitung des Datensatzes:
- Die Daten wurden von www.kaggle.com heruntergeladen: Autoscout24
- Die Daten (csv-file) beinhalten folgende Felder: Marke, Model, KM-Stand, Kraftstoff, Getriebe, Preis, PS, Baujahr und Angebotstyp (insgesamt 9 Spalten)
- Ein zusaetzlicher Datensatz (als json-file) wurde mithilfe chatGPT erstellt und beinhaltet noch das Herstellerland je Automarke.
- Beide Datensaetze werden geprueft und zusammen verbunden.
Doppelte Eintraege und NaN Werte werden geloescht.
Vorerst werden die Numpy und Pandas Bibliotheken benutzt.
Wir werden verschiedene Techniken sehen, um verschiedene Arten von Daten zu simulieren...
import numpy as np
import pandas as pd
cars_org = pd.read_csv('autoscout24-germany-dataset.csv')
cars_org.head()
| mileage | make | model | fuel | gear | offerType | price | hp | year | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 235000 | BMW | 316 | Diesel | Manual | Used | 6800 | 116.0 | 2011 |
| 1 | 92800 | Volkswagen | Golf | Gasoline | Manual | Used | 6877 | 122.0 | 2011 |
| 2 | 149300 | SEAT | Exeo | Gasoline | Manual | Used | 6900 | 160.0 | 2011 |
| 3 | 96200 | Renault | Megane | Gasoline | Manual | Used | 6950 | 110.0 | 2011 |
| 4 | 156000 | Peugeot | 308 | Gasoline | Manual | Used | 6950 | 156.0 | 2011 |
# CHECK: rows in original csv-file
rows0 = len(cars_org)
print (rows0)
46405
country = pd.read_json('cars_and_countries_2.json')
country.drop('index', axis=1, inplace=True)
print (country.columns)
Index(['make', 'country'], dtype='object')
cars_upd = pd.merge(cars_org, country, on='make', how='outer')
cars_upd.head()
| mileage | make | model | fuel | gear | offerType | price | hp | year | country | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 39500 | 9ff | NaN | Gasoline | Manual | Used | 7000 | 20.0 | 2018 | Germany |
| 1 | 21500 | Abarth | 500 | Gasoline | Manual | Used | 11850 | 160.0 | 2015 | Italy |
| 2 | 15000 | Abarth | 595 Competizione | Gasoline | Manual | Used | 23975 | 179.0 | 2020 | Italy |
| 3 | 5 | Abarth | 500 | Gasoline | Manual | Demonstration | 24480 | 179.0 | 2020 | Italy |
| 4 | 5 | Abarth | 500 | Gasoline | Manual | Demonstration | 24480 | 179.0 | 2020 | Italy |
# CHECK: rows in dataset after merging both files
rows1 = len(cars_upd)
print (rows1)
46405
cars_mod = cars_upd.drop_duplicates()
# CHECK: rows in dataset after deleting duplicates
rows2 = len(cars_mod)
print (rows2)
44265
# noch eine zusaetzliche Spalte mit dem Monat wo die Anzeige aufgegeben ist fuer eventuelle zusaetzliche Analyse (random generated data)
import random
#month = [1,2,3,4,5,6,7,8,9,10,11,12]
month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
cars_mod.loc[:, 'ad-month'] = [random.choice(month) for i in range(len(cars_mod))]
cars_mod.sample(5)
C:\Users\mario\AppData\Local\Temp\ipykernel_21732\3370031157.py:5: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy cars_mod.loc[:, 'ad-month'] = [random.choice(month) for i in range(len(cars_mod))]
| mileage | make | model | fuel | gear | offerType | price | hp | year | country | ad-month | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 25186 | 158500 | Opel | Corsa | Diesel | Manual | Used | 3500 | 75.0 | 2011 | Germany | feb |
| 1679 | 28500 | Audi | Q8 | Gasoline | Automatic | Used | 79889 | 340.0 | 2019 | Germany | mar |
| 36127 | 70000 | Suzuki | Splash | Gasoline | Manual | Used | 5199 | 86.0 | 2011 | Japan | sep |
| 3502 | 101900 | BMW | 316 | Gasoline | Manual | Used | 13099 | 136.0 | 2013 | Germany | dec |
| 5487 | 61000 | Chevrolet | Spark | Gasoline | Manual | Used | 3450 | 68.0 | 2011 | USA | feb |
# Erstellung einer Kopie der Daten
cars_mod2 = cars_mod.copy()
# double CHECK: rows after adding randomized data
rows3 = len(cars_mod2)
print (rows3)
44265
NaN = cars_mod2.isnull().any(axis=1).sum()
print (NaN)
1266
cars_fin = cars_mod2.dropna()
# CHECK: rows after deleting the NaN's
rows4 = len(cars_fin)
print (rows4)
42999
cars_fin.head()
| mileage | make | model | fuel | gear | offerType | price | hp | year | country | ad-month | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 21500 | Abarth | 500 | Gasoline | Manual | Used | 11850 | 160.0 | 2015 | Italy | apr |
| 2 | 15000 | Abarth | 595 Competizione | Gasoline | Manual | Used | 23975 | 179.0 | 2020 | Italy | jul |
| 3 | 5 | Abarth | 500 | Gasoline | Manual | Demonstration | 24480 | 179.0 | 2020 | Italy | oct |
| 5 | 61600 | Abarth | 500 | Gasoline | Manual | Demonstration | 11890 | 135.0 | 2014 | Italy | apr |
| 6 | 84510 | Abarth | 595 | Gasoline | Manual | Used | 12490 | 160.0 | 2014 | Italy | feb |
# CHECK: check if there are still some duplicates
dupl_chck = cars_fin[cars_fin.duplicated()]
print(dupl_chck)
Empty DataFrame Columns: [mileage, make, model, fuel, gear, offerType, price, hp, year, country, ad-month] Index: []
Teil 2:¶
Weitere Bereinigung der Daten & Finale Vorbereitung fuer die Analysen:
- Loeschen von unnoetigen Daten (nach Schaetzung)
- Fehlerteufel
- Doublecheck
- groupby() function
Der Finale Datensatz wird als eine neue csv-Datei gespeichert, um sie neu aufzurufen fuer eventuelle weitere Analysen im neuem Notebook.
country_make = cars_fin.groupby('country')['make'].count()
country_make
country China 6 Czech Republic 2737 France 4785 Germany 19584 Italy 1710 Japan 3583 NaN 1 Romania 661 Russia 31 South Korea 1773 Spain 1892 Sweden 779 UK 801 USA 4656 Name: make, dtype: int64
# loeschen des Fehlerteufels "NaN" mit Lambda Funktion
cars_fin1 = cars_fin[~cars_fin.apply(lambda row: row.astype(str).str.contains('NaN', case=False).any(), axis=1)]
country_make1 = cars_fin1.groupby('country')['make'].count()
country_make1
country China 6 Czech Republic 2737 France 4785 Germany 19584 Italy 1710 Japan 3583 Romania 661 Russia 31 South Korea 1773 Spain 1892 Sweden 779 UK 801 USA 4656 Name: make, dtype: int64
# CHECK: rows after update
rows5 = len(cars_fin1)
print (rows5)
42998
print(cars_fin1.describe(include='object'))
make model fuel gear offerType country ad-month count 42998 42998 42998 42998 42998 42998 42998 unique 69 817 11 3 5 13 12 top Volkswagen Golf Gasoline Manual Used Germany aug freq 6680 1450 26533 28031 37805 19584 3662
ge = 'gear'
print(cars_fin1[ge].value_counts())
gear Manual 28031 Automatic 14914 Semi-automatic 53 Name: count, dtype: int64
fin2_upd = cars_fin1[cars_fin1['gear'] != 'Semi-automatic']
print(fin2_upd[ge].value_counts())
gear Manual 28031 Automatic 14914 Name: count, dtype: int64
fu = 'fuel'
print(fin2_upd[fu].value_counts())
fuel Gasoline 26494 Diesel 14470 Electric/Gasoline 1013 Electric 633 CNG 113 LPG 106 Electric/Diesel 48 Others 45 -/- (Fuel) 20 Ethanol 2 Hydrogen 1 Name: count, dtype: int64
fin3_upd = fin2_upd[~fin2_upd['fuel'].isin(['Hydrogen', 'Ethanol', '-/- (Fuel)', 'Others'])]
print(fin3_upd[fu].value_counts())
fuel Gasoline 26494 Diesel 14470 Electric/Gasoline 1013 Electric 633 CNG 113 LPG 106 Electric/Diesel 48 Name: count, dtype: int64
print(fin3_upd.describe(include='object'))
make model fuel gear offerType country ad-month count 42877 42877 42877 42877 42877 42877 42877 unique 69 816 7 2 5 13 12 top Volkswagen Golf Gasoline Manual Used Germany aug freq 6672 1450 26494 27979 37699 19533 3651
of = 'offerType'
print(fin3_upd[of].value_counts())
offerType Used 37699 Demonstration 2160 Pre-registered 1940 Employee's car 1068 New 10 Name: count, dtype: int64
fin3_upd.to_csv('autoscout24-modified-x.csv', index=False)
Teil 3 :¶
In diesem Teil werden einige Plots mit Histogramme dargestellt.
Dazu wird die Bibliothek Matplotlib verwendet.
Beispiel mit Plotbar und Histogram.
import matplotlib.pyplot as plt
country_make1.plot.bar(figsize=(10,5), color='green', edgecolor='red')
plt.title('Makes per Country')
plt.xlabel('Country')
plt.ylabel('Make_number')
Text(0, 0.5, 'Make_number')
cars_fin1.country.hist(figsize=(10,5), color='blue', edgecolor='magenta')
plt.title('Anzahl pro Land')
plt.xlabel('Land')
plt.ylabel('Anzahl Autos')
Text(0, 0.5, 'Anzahl Autos')
Teil 4 : A)¶
Im Teil 4 folgen einige Analysen und Visualisierungen der fertig gestellten Daten.
Ab hier wird der finale neu abgespeicherte Datensatz benutzt.
Auser der Bibliotheken Pandas & Matplotlib, wird hier auch Seaborn verwendet.
Folgen einige Beispiele...
# import: Seaborn
import seaborn as sns
cars24x = pd.read_csv('autoscout24-modified-x.csv')
cars24x.head()
| mileage | make | model | fuel | gear | offerType | price | hp | year | country | ad-month | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 21500 | Abarth | 500 | Gasoline | Manual | Used | 11850 | 160.0 | 2015 | Italy | apr |
| 1 | 15000 | Abarth | 595 Competizione | Gasoline | Manual | Used | 23975 | 179.0 | 2020 | Italy | jul |
| 2 | 5 | Abarth | 500 | Gasoline | Manual | Demonstration | 24480 | 179.0 | 2020 | Italy | oct |
| 3 | 61600 | Abarth | 500 | Gasoline | Manual | Demonstration | 11890 | 135.0 | 2014 | Italy | apr |
| 4 | 84510 | Abarth | 595 | Gasoline | Manual | Used | 12490 | 160.0 | 2014 | Italy | feb |
print(cars24x.describe())
mileage price hp year count 4.287700e+04 4.287700e+04 42877.000000 42877.000000 mean 7.266792e+04 1.663444e+04 134.054015 2015.931338 std 6.239793e+04 1.962369e+04 75.548088 3.113938 min 0.000000e+00 1.100000e+03 1.000000 2011.000000 25% 2.170000e+04 7.490000e+03 86.000000 2013.000000 50% 6.166100e+04 1.099000e+04 116.000000 2016.000000 75% 1.065500e+05 1.974500e+04 150.000000 2019.000000 max 1.111111e+06 1.199900e+06 850.000000 2021.000000
print(cars24x.describe(include='object'))
make model fuel gear offerType country ad-month count 42877 42877 42877 42877 42877 42877 42877 unique 69 816 7 2 5 13 12 top Volkswagen Golf Gasoline Manual Used Germany aug freq 6672 1450 26494 27979 37699 19533 3651
cars_per_country = cars24x.groupby('country')['make'].count()
print(cars_per_country)
country China 6 Czech Republic 2731 France 4764 Germany 19533 Italy 1702 Japan 3569 Romania 661 Russia 31 South Korea 1769 Spain 1889 Sweden 778 UK 801 USA 4643 Name: make, dtype: int64
cars_per_country.plot.bar(figsize=(10,5), color='green', edgecolor='red')
plt.title('Makes per Country')
plt.xlabel('Country')
plt.ylabel('Make_number')
plt.show()
plt.figure(figsize=(12,6))
# Countplot
sns.countplot(data=cars24x, x='year', hue='gear', palette='Set2')
plt.title('Distribution of gear by year of production')
plt.xlabel('year')
plt.ylabel('number of cars')
plt.xticks(rotation=45)
plt.show()
make = 'BMW'
#make = 'Porsche'
#make = 'Renault'
# ...
df_model = cars24x[cars24x['make'] == make]
# Top 20 models
top_20_models = df_model['model'].value_counts().head(20).index
# Filtering dataframe only for top 20 models
df_model_top_20 = df_model[df_model['model'].isin(top_20_models)]
plt.figure(figsize=(12, 16))
# Horizontal countplot for top 20 models
sns.countplot(
data=df_model_top_20,
y='model',
hue='model',
order=top_20_models,
legend=False
)
plt.title(f'Top 20 models for {make}', fontsize=10)
plt.xlabel('Number of models', fontsize=8)
plt.ylabel('Model', fontsize=8)
plt.show()
ads = cars24x['ad-month'].str.lower().str[:3].value_counts()\
.reindex(['jan', 'feb', 'mar', 'apr', 'may', 'jun',
'jul', 'aug', 'sep', 'oct', 'nov', 'dec'])
plt.figure(figsize=(12, 6))
sns.lineplot(
x=ads.index,
y=ads.values,
marker='o',
linewidth=3,
color='#E53935',
markersize=9
)
plt.title('Darstellung: Anzeigen pro Monat', pad=20, fontsize=14)
plt.xlabel('Monat', labelpad=10)
plt.ylabel('Anzeigen', labelpad=10)
plt.grid(axis='y', alpha=0.3)
y_min = max(0, ads.min() - 100)
y_max = ads.max() + 100
plt.ylim(y_min, y_max)
for x, y in zip(ads.index, ads.values):
plt.text(x, y + (y_max - y_min)*0.02, f"{y:,}", ha='center', va='bottom', fontsize=9)
plt.tight_layout()
plt.show()
Teil 4 : B)¶
Im Teil 4.B --> einige weitere Visualisierungen mit Matplotlib & Seaborn.
mit einer Interaktiven Visualisierung - nur neue Autos!
Der finale Datensatz wird verwendet - "autoscout24-modified-x.csv"
new_cars = cars24x[cars24x['offerType'] == 'New']
pd.set_option('display.max_columns', None)
pd.set_option('display.float_format', '{:.2f}'.format) # Zahl formatierung
# interaktive visualisierung
from IPython.display import display
print(f"In der Datenbank wurden {len(new_cars)} GANZ NEUE Autos gefunden:")
display(new_cars.style
.background_gradient(subset=['price'], cmap='YlOrRd')
.format({'price': '€{:.2f}'}) # Preis formatierung
.set_caption('Liste der neuen Autos')
.set_properties(**{'text-align': 'left'})
)
In der Datenbank wurden 10 GANZ NEUE Autos gefunden:
| mileage | make | model | fuel | gear | offerType | price | hp | year | country | ad-month | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 5109 | 380 | Bentley | Bentayga | Diesel | Automatic | New | €192780.00 | 435.000000 | 2021 | UK | nov |
| 7047 | 47 | Ferrari | F8 Tributo | Gasoline | Automatic | New | €304900.00 | 721.000000 | 2021 | Italy | mar |
| 13156 | 0 | Hyundai | i10 | Gasoline | Manual | New | €12579.00 | 67.000000 | 2021 | South Korea | apr |
| 15063 | 17 | Land | Rover Range Rover Sport | Gasoline | Automatic | New | €131980.00 | 575.000000 | 2021 | UK | apr |
| 30221 | 5 | SEAT | Ibiza | Gasoline | Manual | New | €15990.00 | 80.000000 | 2021 | Spain | oct |
| 30222 | 5 | SEAT | Ibiza | Gasoline | Manual | New | €16690.00 | 95.000000 | 2021 | Spain | mar |
| 30226 | 5 | SEAT | Arona | Gasoline | Manual | New | €17990.00 | 95.000000 | 2021 | Spain | jun |
| 30227 | 5 | SEAT | Arona | Gasoline | Automatic | New | €22690.00 | 110.000000 | 2021 | Spain | may |
| 32942 | 5 | Skoda | Karoq | Gasoline | Automatic | New | €36490.00 | 150.000000 | 2021 | Czech Republic | jun |
| 32950 | 5 | Skoda | Superb | Electric/Gasoline | Automatic | New | €52990.00 | 156.000000 | 2021 | Czech Republic | may |
avg_price_by_year = cars24x.groupby('year', as_index=False)['price'].mean()
plt.figure(figsize=(12, 6))
sns.lineplot(
data=avg_price_by_year,
x='year',
y='price',
marker='o',
linewidth=2.5,
color='crimson'
)
plt.title('price AVG according to production year')
plt.xlabel('year of production')
plt.ylabel('AVG price')
plt.grid(True)
plt.show()
Teil 5 :¶
Weitere Visualisierungen mit Matplotlib & Seaborn.
- BOXPLOT Beispiele
- Zusaetzliche Analysen (Barplots & Lineplots)
plt.figure(figsize=(12, 6))
sns.boxplot(data=cars24x, x='make', y='price')
plt.title('Preisverteilung nach Marken')
plt.xlabel('Make')
plt.ylabel('Price')
plt.xticks(rotation=90)
plt.tight_layout()
plt.show()
plt.figure(figsize=(12, 6))
sns.boxplot(
data=cars24x,
x='offerType',
y='mileage',
hue='offerType',
showfliers=False,
palette='Set2'
)
plt.title('KM-Stand vs Angebotstyp', fontsize=14)
plt.xlabel('Angebotstyp', fontsize=12)
plt.ylabel('KM-Stand', fontsize=12)
plt.show()
plt.figure(figsize=(12, 6))
sns.boxplot(
data=cars24x,
x='offerType',
y='price',
hue='offerType',
showfliers=False,
palette='Set2'
)
plt.title('Preis vs Angebotstyp', fontsize=14)
plt.xlabel('Angebotstyp', fontsize=12)
plt.ylabel('Preis', fontsize=12)
plt.show()
avg_hp = cars24x.groupby('make', as_index=False)['hp'].mean().sort_values('hp', ascending=False)
plt.figure(figsize=(14, 8))
sns.barplot(
data=avg_hp,
x='make',
y='hp',
hue='make',
palette='rocket'
)
plt.title('hp avg according to make')
plt.xlabel('make')
plt.ylabel('hp avg')
plt.xticks(rotation=90, ha='right')
plt.tight_layout()
plt.show()
plt.figure(figsize=(12, 6))
top_marke = cars24x['make'].value_counts().nlargest(10)
sns.barplot(x=top_marke.index, y=top_marke.values, palette='rainbow', hue=top_marke.index)
plt.title('Top 10 Automarken', fontsize=14)
plt.xlabel('Marke', fontsize=12)
plt.ylabel('Anzahl', fontsize=12)
plt.xticks(rotation=45)
plt.tight_layout()
for i, value in enumerate(top_marke.head(20).values):
plt.text(i, value + 0.5, str(value), ha='center', va='bottom')
plt.show()
cars24x['make_model'] = cars24x['make'] + ' ' + cars24x['model']
top_model = cars24x['make_model'].value_counts().nlargest(20)
plt.figure(figsize=(12, 6))
sns.barplot(x=top_model.index, y=top_model.values, palette='Set3', hue=top_model.index)
plt.title('Top 20 Modele', fontsize=14)
plt.xlabel('Model', fontsize=12)
plt.ylabel('Anzahl', fontsize=12)
plt.xticks(rotation=80)
plt.tight_layout()
for i, value in enumerate(top_model.head(20).values):
plt.text(i, value + 0.5, str(value), ha='center', va='bottom')
plt.show()
# Kategorie fuer KM:
bins = [0, 100000, 200000, 300000, 400000, float('inf')]
labels = ['<100k', '100k-200k', '200k-300k', '300k-400k', '>400k']
cars24x['km_category'] = pd.cut(cars24x['mileage'], bins=bins, labels=labels, right=False)
# groub by KM-kategorie & Kalkulation des durchschnittlichen Preises
avg_price_by_km = cars24x.groupby('km_category', as_index=False, observed=True)['price'].mean()
# Visualisierung
plt.figure(figsize=(12, 6))
sns.barplot(
data=avg_price_by_km,
x='km_category',
y='price',
hue='km_category',
palette='viridis',
order=labels,
legend=False
)
plt.title('Preis nach KM-Stand')
plt.xlabel('KM-Stand')
plt.ylabel('Preis AVG')
plt.grid(True, axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()
motor_tr = cars24x.groupby(['year', 'fuel'], as_index=False).size()
plt.figure(figsize=(14, 7))
sns.lineplot(
data=motor_tr,
x='year',
y='size',
hue='fuel',
style='fuel',
markers=True,
dashes=False,
linewidth=2.5,
palette='viridis'
)
plt.title('Motor Trend durch die Jahre', fontsize=16)
plt.xlabel('Baujahr', fontsize=12)
plt.ylabel('Anzahl der Fahrzeuge', fontsize=12)
plt.grid(True)
plt.legend(title='Motor', bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
plt.show()
motor_pro = cars24x.groupby(['year', 'fuel']).size().unstack().fillna(0)
motor_pro = motor_pro.div(motor_pro.sum(axis=1), axis=0) * 100
plt.figure(figsize=(14, 7))
sns.lineplot(
data=motor_pro.reset_index().melt(id_vars='year'),
x='year',
y='value',
hue='fuel',
style='fuel',
linewidth=2.5
)
plt.title('Motor Trend durch die Jahre (%)', fontsize=16)
plt.xlabel('Baujahr', fontsize=12)
plt.ylabel('Prozentsatz (%)', fontsize=12)
plt.grid(True)
plt.legend(title='Motor', bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
plt.show()
plt.figure(figsize=(14, 7))
sns.lineplot(
data=cars24x,
x='year',
y='hp',
estimator='median',
errorbar=None,
color='red',
linewidth=2.5,
label='median'
)
sns.lineplot(
data=cars24x,
x='year',
y='hp',
estimator='mean',
errorbar=None,
color='blue',
linewidth=2.5,
label='average'
)
plt.title('PS Entwicklung durch Jahre', fontsize=16)
plt.xlabel('Produktionsjahr', fontsize=12)
plt.ylabel('PS', fontsize=12)
plt.grid(True)
plt.legend()
plt.show()
Teil 6 :¶
Visualisierung mit Dash!
Auser der Bibliothek Pandas, wird hier auch Dash und Plotly verwendet.
Die callback Funktion wird benutzt. Eine beliebige Automarke kann ausgewaehlt werden und als Ergebnis wird die Anzahl aller Modele dieser Automarke angezeigt.
import dash
from dash import Dash, html, dcc, callback, Output, Input
import plotly.express as px
print("Anzahl der verschiedenen Automarken:", len(cars24x['make'].unique()))
print("Beispiel Automarken:", cars24x['make'].unique()[21:29])
print("Insgesammt Modele:", len(cars24x['model'].unique()))
Anzahl der verschiedenen Automarken: 69 Beispiel Automarken: ['Dodge' 'Estrima' 'FISKER' 'Ferrari' 'Fiat' 'Ford' 'Honda' 'Hyundai'] Insgesammt Modele: 816
cars24x = pd.read_csv('autoscout24-modified-x.csv')
app = Dash(__name__)
app.layout = html.Div([
html.H1(children='Analyse der Modele nach Marke', style={'textAlign':'center'}),
dcc.Dropdown(
id='dropdown-selection',
options=[{'label': make, 'value': make} for make in sorted(cars24x['make'].unique())], # sorted
value=cars24x['make'].iloc[0] # die erste AutoMarke als Startmarke
),
dcc.Graph(id='graph-content')
])
@callback(
Output('graph-content', 'figure'),
Input('dropdown-selection', 'value')
)
def update_graph(selected_make):
dff = cars24x[cars24x['make'] == selected_make]
model_counts = dff['model'].value_counts().reset_index()
model_counts.columns = ['model', 'count']
fig = px.bar(
model_counts,
x='model',
y='count',
title=f'Anzahl der Modele fuer die Marke: {selected_make}',
labels={'model': 'Model', 'count': 'Anzahl der Fahrzeuge'},
height=600
)
return fig
if __name__ == '__main__':
app.run(debug=True, port=8088)
# Daten
cars24x = pd.read_csv('autoscout24-modified-x.csv')
app = Dash(__name__)
app.layout = html.Div([
html.H1(children='Analyse der Modele nach Marke', style={'textAlign':'center'}),
dcc.Dropdown(
id='dropdown-selection',
options=[{'label': make, 'value': make} for make in sorted(cars24x['make'].unique())],
value=cars24x['make'].iloc[0] # die erste AutoMarke als Startmarke
),
dcc.Graph(id='graph-content')
])
@callback(
Output('graph-content', 'figure'),
Input('dropdown-selection', 'value')
)
def update_graph(selected_make):
dff = cars24x[cars24x['make'] == selected_make]
model_counts = dff['model'].value_counts().reset_index()
model_counts.columns = ['model', 'count']
fig = px.bar(
model_counts,
x='model',
y='count',
title=f'Anzahl der Modele fuer die Marke: {selected_make}',
labels={'model': 'Model', 'count': 'Anzahl der Fahrzeuge'},
color='model', # color according model
color_discrete_sequence=px.colors.qualitative.Plotly, # color palette
height=600
)
fig.update_layout(
xaxis={'categoryorder': 'total descending'},
showlegend=True # show/hide legend
)
return fig
if __name__ == '__main__':
app.run(debug=True, port=8087)
Teil 7 :¶
Darstellung der Autohersteller auf der Welt- und Europa-karte.
In diesem Teil werden einige zusaetzliche Tests und Visualisierungen gemacht, dazu wird hier die Cartopy-Bibliothek benutzt. downloaded from --> www.naturalearthdata.com /downloads/10m-cultural-vectors/10m-admin-0-countries/ --> file: "ne_10m_admin_0_countries.zip"
2 Beispiele mit cartopy:
- Europakarte - simple (gelungen)
- Weltkarte (failed), aber es funktioniert halbherzig, die Laender mit mehr Automarken werden dunkler angezeigt, und diejenigen mit weniger werden heller angezeigt. Es kommt ein Warning: Legende unterstützt kein FeatureArtist-Instanz!
print(sorted(cars24x['country'].unique()))
['China', 'Czech Republic', 'France', 'Germany', 'Italy', 'Japan', 'Romania', 'Russia', 'South Korea', 'Spain', 'Sweden', 'UK', 'USA']
from cartopy.io import shapereader
from cartopy import crs
import matplotlib.pyplot as plt
import cartopy.crs as crs
import cartopy.io.shapereader as shapereader
only_eu = cars24x['country'].value_counts()
plt.figure(figsize=(12, 8))
ax = plt.axes(projection=crs.PlateCarree())
ax.set_extent([-11, 33, 33, 66])
reader = shapereader.Reader(
shapereader.natural_earth(
resolution='10m',
category='cultural',
name='admin_0_countries'
)
)
for country in reader.records():
country_name = country.attributes.get('NAME_LONG')
if country_name in only_eu.index:
ax.add_geometries(
[country.geometry],
crs.PlateCarree(),
facecolor='blue',
edgecolor='black',
linewidth=0.5
)
plt.title('Autohersteller – EU')
plt.show()
import matplotlib.pyplot as plt
import cartopy.crs as crs
import cartopy.io.shapereader as shapereader
import matplotlib.cm as cm
import matplotlib.colors as colors
# 1. podaci
countrycount = cars24x['country'].value_counts()
# 2. mapa
plt.figure(figsize=(16, 10))
ax = plt.axes(projection=crs.PlateCarree())
ax.set_global()
# 3. Natural Earth shapefile (AUTO download)
reader = shapereader.Reader(
shapereader.natural_earth(
resolution='10m',
category='cultural',
name='admin_0_countries'
)
)
# 4. normalizacija boja
max_count = countrycount.max() if not countrycount.empty else 1
norm = colors.Normalize(vmin=0, vmax=max_count)
cmap = cm.Blues
# 5. crtanje drzava
for country in reader.records():
countryname = (
country.attributes.get('NAME_LONG')
or country.attributes.get('ADMIN')
or country.attributes.get('NAME')
or country.attributes.get('SOVEREIGNT')
)
if countryname in countrycount.index:
ax.add_geometries(
[country.geometry],
crs.PlateCarree(),
facecolor=cmap(norm(countrycount[countryname])),
edgecolor='black',
linewidth=0.5
)
else:
ax.add_geometries(
[country.geometry],
crs.PlateCarree(),
facecolor='#f2f2f2',
edgecolor='#cccccc',
linewidth=0.3
)
# 6. colorbar
sm = cm.ScalarMappable(norm=norm, cmap=cmap)
sm.set_array([])
cbar = plt.colorbar(sm, ax=ax, orientation='vertical', pad=0.02)
cbar.set_label('Broj vozila / proizvođača')
# 7. naslov
plt.title(
'Zemlje proizvođača automobila\n(što tamnije – više vozila)',
fontsize=14,
pad=20
)
plt.show()
Teil 8 :¶
Im Teil 8 zusaetzliche Dash Tests (leider keine Zeit mehr...)
from dash import dash_table
app = Dash()
app.layout = [html.Div(children='My Cars'),
dash_table.DataTable(data=cars24x.to_dict('records'), page_size=10),
dcc.Graph(figure=px.histogram(cars24x, x='make', y='model', histfunc='count'))
]
if __name__ == '__main__':
app.run(debug=True, port=8085)
app = Dash(__name__)
app.layout = html.Div([
html.Div(children='My Cars'),
html.Hr(),
dcc.RadioItems(
options=['mileage', 'hp'],
value='hp',
id='controls-and-radio-item'
),
dash_table.DataTable(
data=cars24x.to_dict('records'),
page_size=10
),
dcc.Graph(
id='controls-and-graph',
figure=px.histogram(cars24x, x='make', y='model', histfunc='count')
)
])
@callback(
Output(component_id='controls-and-graph', component_property='figure'),
Input(component_id='controls-and-radio-item', component_property='value')
)
def update_graph(col_chosen):
fig = px.histogram(cars24x, x='make', y=col_chosen, histfunc='count')
return fig
if __name__ == '__main__':
app.run(debug=True, port=8041)