Data Science: Handling Missing Values
Data Science: Handling Missing Values
Determine which club had the most and Predict Exam Scores based on Hours
least number of representatives at park Determine which year produced the Studied.
runs. games with the highest average score.
# Scatterplot for relationship between 'Hours
club_rep = [Link]('club') games_prod = [Link]('release_year') Studied' and 'Exam Score'
['name'].nunique() ['score'].mean() [Link](x='Hours Studied', y='Exam
most_rep = club_rep.agg(['idxmax', 'max']) highest_avg = games_prod.agg(['idxmax', Score', data=df)
least_rep = club_rep.agg(['idxmin', 'min']) 'max']) [Link]('Relationship between Hours Studied
print(club_rep) print('\n This is it:', games_prod) and Exam Score')
print("This is it:", most_rep) print('\n This is it:', highest_avg) [Link]('Hours Studied')
print("This is it:", least_rep) [Link]('Exam Score')
[Link](True)
Determine what was the mean age of Provide the Python Jupyter Notebook [Link]()
the runners from the Mansfield club. code to find the platform that has the
least games. # Extracting the columns and convert to
df_mansfield = df[df['club'] == 'Mansfield'] NumPY arrays
mean_age = df_mansfield['age'].mean() df_games = [Link]('platform') X = df[['Hours Studied']]
print("This is it:", mean_age) ['title'].count() y = df['Exam Score']
print('This is it', df['age'].dtype) # For least_games = df_games.agg(['idxmin',
Diagnostic 'min']) # Splitting the data into training and testing
print('\n This is it:', df_games) sets
print('\n This is it:', least_games) X_train, X_test, y_train, y_test =
Determine the most popular park for of games is: ', least_games_platform) train_test_split(X, y, test_size=0.2,
the runners. random_state=42)
Integrar essas informações por meio de Determine which Country vaccinated Excluded the numbers for the European
junções (merges) e realizar uma análise the least number of people in October Union and create an appropriate chart
exploratória dos dados. 2021. Do not include the European that shows the most and to least
Union. popular vaccines in 2021
user_usage =
pd.read_csv("user_usage.csv") df['date'] = pd.to_datetime(df['date']) df['date'] = pd.to_datetime(df['date'],
user_device = df_October_2021 = df[(df['date'].[Link] == dayfirst=True)
pd.read_csv("user_device.csv") 2021) & (df['date'].[Link] == 10) & df_no_european = df[(df['location'] !=
android_devices = (df['location'] != 'European Union')] 'European Union') & (df['date'].[Link] ==
pd.read_csv("android_devices.csv") people_vaccinated = 2021)]
df_October_2021.groupby('location') vaccination =
print(user_usage.head(), '\n') ['total_vaccinations'].count().sort_index() df_no_european.groupby('vaccine')
print(user_device.head(), '\n') least_vaccination_country = ['total_vaccinations'].sum().sort_index()
print(android_devices.head(), '\n') people_vaccinated.idxmin() most_vac = [Link]()
# user_usage.info() vaccine_quantity = people_vaccinated.min() vaccine_fig_most = [Link]()
# user_device.info() print(f"\n This is the number of people least_vac = [Link]()
# android_devices.info() vaccinated in their respective locations:\n vaccine_fig_least = [Link]()
{people_vaccinated} and the quantity for extreme_vaccines =
merged_df = [Link](user_usage, the least vaccinated population is [Link][[least_vac, most_vac]]
user_device, on='use_id', how='left') {vaccine_quantity}.")
print(f"\n This is the non-European least
display(merged_df.head()) popular vaccine, {least_vac}:
display(merged_df.tail()) Determine whether the European Union {vaccine_fig_least}, and the most popular
or the United States Vaccinated more vaccines is {most_vac}:
eventual_issues = merged_df.isnull().sum() people. {vaccine_fig_most}")
print(eventual_issues)
df_eu_us = df[df['location'].isin(['European [Link](figsize=(10, 10))
merged_df.fillna({ Union', 'United States'])] extreme_vaccines.plot(kind='bar',
'user_id': -1, countries_vaccination = color=['green', 'blue'], edgecolor='black')
'platform': 'Unknown', df_eu_us.groupby('location') [Link]('Most and Least Popular Vaccines')
'platform_version': 'Unknown', ['total_vaccinations'].sum() [Link]('Vaccines')
'device': 'Unknown', most_vaccinator = [Link]('Quantity')
'use_type_id': -1 countries_vaccination.idxmax() [Link](rotation=45)
}, inplace=True) vaccines_applied = [Link](axis='y', linestyle='--', alpha=0.7)
countries_vaccination.max() plt.tight_layout()
fixed_issues = merged_df.isnull().sum() [Link]()
print(fixed_issues, '\n') print(f"\nThis is the country that most
vaccinated, {most_vaccinator}: [Link]("[Link]")
final_df = [Link](merged_df, {vaccines_applied}")
android_devices, left_on='device',
right_on='Device', how='left') Determine if France or Germany
print(final_df.isnull().sum()) Determine the most vaccinations were Vaccinated the most people in October
given in Hong Kong. 2022.
fixing_again = final_df.fillna({
'Retail Branding': 'Unknown', df_hong_kong = df[df['location'] == 'Hong df['date'] = pd.to_datetime(df['date'],
'Marketing Name': 'Unknown', Kong'] dayfirst=True)
'Device': 'Unknown', vac_by_date= df_hong_kong.groupby('date') df_oct_2022 = df[(df['date'].[Link] ==
'Model': 'Unknown' ['total_vaccinations'].sum() 10) & (df['date'].[Link] == 2022)]
}, inplace=True) most_vac = vac_by_date.idxmax() country_vaccinations =
vac_figure = vac_by_date.max() df_oct_2022.groupby('location')
print(final_df.isnull().sum()) ['total_vaccinations'].sum()
print(f'\n The most vaccinations in Hong top_country =
# Analytical Part Kong were {vac_figure} and happened on country_vaccinations.idxmax()
{most_vac}') top_value = country_vaccinations.max()
# Check if it was France or Germany variações e relação entre as modelo favorecer ou prejudicar
if top_country in ['France', 'Germany']: linhas. certos grupos.
print(f"{top_country} vaccinated the most 4. Como interpretar uma tabela 24. O que define a GDPR em
in October 2022 with {top_value} doses.") 4x4 com foco na linha 3, por relação aos dados?
else: exemplo? → Conjunto de regras da UE sobre
print(f"{top_country} vaccinated the most → Analisa-se apenas os dados da privacidade e proteção de dados
in October 2022 with {top_value} doses. So, terceira linha, comparando os pessoais.
neither France nor Germany were top.") valores nas colunas. 25. Por que a explicabilidade
5. Para que serve o método (explainability) é importante
groupby() no pandas? em modelos de IA?
Determine the least-used vaccine in → Agrupa dados por uma coluna → Garante transparência,
South Korea between April 2021 and para aplicar funções agregadas confiança e permite auditoria dos
April 2022. como mean() ou sum(). resultados.
6. Qual o uso de [Link]()
df['date'] = pd.to_datetime(df['date'], em um dataset numérico?
dayfirst=True) → Visualizar correlações entre
df_south_korea = df[(df['location'] == 'South variáveis numéricas.
Korea') & (df['date'].[Link] == 4) & 7. Explique o que é um gráfico de
(df['date'].[Link](2021, 2022))] dispersão e quando usá-lo.
period_of_vaccines = → Mostra a relação entre duas
df_south_korea.groupby('vaccine') variáveis numéricas; útil para
['total_vaccinations'].sum() detectar padrões.
least_sk = period_of_vaccines.idxmin() 8. Como identificar valores
least_fig = period_of_vaccines.min() ausentes em um DataFrame?
→ Usando [Link]().sum().
print(f"\n The {least_sk} was the least 9. Como substituir valores
administrated vaccine in South Korea. Only ausentes por uma string
{least_fig} applied") 'Unknown'?
→ df['coluna'] =
df['coluna'].fillna('Unknown').
Create a bar chart to show the top 5 10. O que value_counts() faz?
countries that used the → Conta a frequência de cada
Oxford/AstraZeneca in 2021. valor único em uma coluna.
11. O que é regressão linear
df['date'] = pd.to_datetime(df['date'], simples?
dayfirst=True) → Modelo que relaciona uma
df_astrazeneca_2021 = df[(df['vaccine'] == variável independente a uma
"Oxford/AstraZeneca") & (df['date'].[Link] variável dependente por uma linha
== 2021)] reta.
top_5 = 12. Qual é o propósito do
df_astrazeneca_2021.groupby('location') train_test_split()?
['total_vaccinations'].sum() → Dividir os dados em treino e
teste para avaliar o desempenho
print("\n This is", df_astrazeneca_2021) do modelo.
print("\n This is", top_5) 13. Cite duas métricas comuns de
avaliação em regressão linear.
[Link](figsize=(10, 10)) → r2_score e mean_squared_error.
top_5.plot(kind='bar', color='blue', 14. Como representar
edgecolor='black') graficamente a linha de
[Link]('Top 5 vaccines') regressão sobre os dados?
[Link]('Countries') → Usar [Link]() sobre o
[Link]('Quantity') [Link]().
[Link](rotation=45) 15. Para que serve o
[Link](axis='y', linestyle='--', alpha=0.7) LinearRegression() do sklearn?
plt.tight_layout() → Criar e treinar um modelo de
[Link]() regressão linear.
16. Quando é necessário usar
[Link]("vaccination_top_5.png") Dask em vez de pandas?
→ Quando os dados são muito
grandes para caber na memória.
Determine which vaccine was the most 17. Cite uma vantagem do
used in the United States for each of processamento paralelo.
the months provided. → Reduz o tempo de execução
dividindo tarefas entre múltiplos
df_usa = df[df['location'] == 'United States'] núcleos.
range_of_date = df_usa.groupby(['date', 18. O que é um DAG em sistemas
'vaccine'])['total_vaccinations'].sum() distribuídos?
most_common_per_date = → Grafo acíclico direcionado que
range_of_date.agg(['idxmax', 'max']) # representa dependências entre
Element and Figure of Max in the same tarefas.
line. 19. Por que a serialização é
importante em Big Data?
print(f"\n This is it:", range_of_date) → Permite salvar e transferir
print(f"\n This is it:", objetos complexos entre nós de
most_common_per_date) processamento.
20. O que é um autovalor
(eigenvalue)?
→ Valor escalar que, ao multiplicar
1. Explique brevemente os
um vetor próprio, não altera sua
quatro estágios do ciclo de
direção.
vida dos dados.
21. Qual é o objetivo da
→ Aquisição, pré-processamento,
diagonalização de matrizes?
análise/modelagem,
→ Simplificar cálculos, como
interpretação/comunicação.
potências de matrizes e sistemas
2. Como criar manualmente um
lineares.
DataFrame simples com
22. Como verificar se uma matriz é
pandas?
diagonalizável?
→ Usando [Link]({ 'nome':
→ Checar se possui número
['Ana'], 'idade': [22] }).
suficiente de autovetores
3. Ao observar um gráfico de
linearmente independentes.
linha com dois parâmetros, o
23. O que é viés algorítmico
que deve ser analisado?
(algorithmic bias)?
→ Tendência (aumenta/diminui),
→ Tendência sistemática de um