-
-
Save rg3915/5fb3a2e7338115bc92e82b7a9a2b372b to your computer and use it in GitHub Desktop.
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"import names\n", | |
"import pandas as pd\n", | |
"import numpy as np" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 2, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"def gen_names(max_value):\n", | |
" persons = []\n", | |
" for _ in range(max_value):\n", | |
" first_name = names.get_first_name()\n", | |
" last_name = names.get_last_name()\n", | |
" full_name = '%s %s' % (first_name, last_name)\n", | |
" email = '%[email protected]' % first_name.lower()\n", | |
" ctx = (full_name, email)\n", | |
" persons.append(ctx)\n", | |
" return persons" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 3, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"names = gen_names(100)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 4, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"df = pd.DataFrame(names, columns=('NAME', 'EMAIL'))" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 5, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"data": { | |
"text/html": [ | |
"<div>\n", | |
"<style>\n", | |
" .dataframe thead tr:only-child th {\n", | |
" text-align: right;\n", | |
" }\n", | |
"\n", | |
" .dataframe thead th {\n", | |
" text-align: left;\n", | |
" }\n", | |
"\n", | |
" .dataframe tbody tr th {\n", | |
" vertical-align: top;\n", | |
" }\n", | |
"</style>\n", | |
"<table border=\"1\" class=\"dataframe\">\n", | |
" <thead>\n", | |
" <tr style=\"text-align: right;\">\n", | |
" <th></th>\n", | |
" <th>NAME</th>\n", | |
" <th>EMAIL</th>\n", | |
" </tr>\n", | |
" </thead>\n", | |
" <tbody>\n", | |
" <tr>\n", | |
" <th>68</th>\n", | |
" <td>Albert Cunningham</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>72</th>\n", | |
" <td>Allen Martinez</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>73</th>\n", | |
" <td>Amalia Mouret</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>62</th>\n", | |
" <td>Amanda Mcmahan</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>28</th>\n", | |
" <td>Ann Rountree</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" </tbody>\n", | |
"</table>\n", | |
"</div>" | |
], | |
"text/plain": [ | |
" NAME EMAIL\n", | |
"68 Albert Cunningham [email protected]\n", | |
"72 Allen Martinez [email protected]\n", | |
"73 Amalia Mouret [email protected]\n", | |
"62 Amanda Mcmahan [email protected]\n", | |
"28 Ann Rountree [email protected]" | |
] | |
}, | |
"execution_count": 5, | |
"metadata": {}, | |
"output_type": "execute_result" | |
} | |
], | |
"source": [ | |
"df.sort_values(by=['EMAIL']).head()" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 6, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"data": { | |
"text/html": [ | |
"<div>\n", | |
"<style>\n", | |
" .dataframe thead tr:only-child th {\n", | |
" text-align: right;\n", | |
" }\n", | |
"\n", | |
" .dataframe thead th {\n", | |
" text-align: left;\n", | |
" }\n", | |
"\n", | |
" .dataframe tbody tr th {\n", | |
" vertical-align: top;\n", | |
" }\n", | |
"</style>\n", | |
"<table border=\"1\" class=\"dataframe\">\n", | |
" <thead>\n", | |
" <tr style=\"text-align: right;\">\n", | |
" <th></th>\n", | |
" <th>NAME</th>\n", | |
" <th>EMAIL</th>\n", | |
" </tr>\n", | |
" </thead>\n", | |
" <tbody>\n", | |
" <tr>\n", | |
" <th>16</th>\n", | |
" <td>Gregory Crittendon</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>54</th>\n", | |
" <td>Gregory Thomson</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>39</th>\n", | |
" <td>Juan Brown</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>86</th>\n", | |
" <td>Juan May</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>58</th>\n", | |
" <td>Kathleen Anderson</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>74</th>\n", | |
" <td>Kathleen Webb</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>53</th>\n", | |
" <td>Paul Nelson</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>69</th>\n", | |
" <td>Paul Morris</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>0</th>\n", | |
" <td>Rene Warthen</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>24</th>\n", | |
" <td>Rene Kidd</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>25</th>\n", | |
" <td>William Hunter</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>47</th>\n", | |
" <td>William Hayes</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" </tbody>\n", | |
"</table>\n", | |
"</div>" | |
], | |
"text/plain": [ | |
" NAME EMAIL\n", | |
"16 Gregory Crittendon [email protected]\n", | |
"54 Gregory Thomson [email protected]\n", | |
"39 Juan Brown [email protected]\n", | |
"86 Juan May [email protected]\n", | |
"58 Kathleen Anderson [email protected]\n", | |
"74 Kathleen Webb [email protected]\n", | |
"53 Paul Nelson [email protected]\n", | |
"69 Paul Morris [email protected]\n", | |
"0 Rene Warthen [email protected]\n", | |
"24 Rene Kidd [email protected]\n", | |
"25 William Hunter [email protected]\n", | |
"47 William Hayes [email protected]" | |
] | |
}, | |
"execution_count": 6, | |
"metadata": {}, | |
"output_type": "execute_result" | |
} | |
], | |
"source": [ | |
"email = df['EMAIL']\n", | |
"dfd = df[email.isin(email[email.duplicated()])]\n", | |
"dfd.sort_values(by=['EMAIL'])" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 7, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"dffinal = df.drop_duplicates('EMAIL').sort_values(by=['EMAIL'])" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 8, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"data": { | |
"text/html": [ | |
"<div>\n", | |
"<style>\n", | |
" .dataframe thead tr:only-child th {\n", | |
" text-align: right;\n", | |
" }\n", | |
"\n", | |
" .dataframe thead th {\n", | |
" text-align: left;\n", | |
" }\n", | |
"\n", | |
" .dataframe tbody tr th {\n", | |
" vertical-align: top;\n", | |
" }\n", | |
"</style>\n", | |
"<table border=\"1\" class=\"dataframe\">\n", | |
" <thead>\n", | |
" <tr style=\"text-align: right;\">\n", | |
" <th></th>\n", | |
" <th>index</th>\n", | |
" <th>NAME</th>\n", | |
" <th>EMAIL</th>\n", | |
" </tr>\n", | |
" </thead>\n", | |
" <tbody>\n", | |
" <tr>\n", | |
" <th>0</th>\n", | |
" <td>68</td>\n", | |
" <td>Albert Cunningham</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>1</th>\n", | |
" <td>72</td>\n", | |
" <td>Allen Martinez</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>2</th>\n", | |
" <td>73</td>\n", | |
" <td>Amalia Mouret</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>3</th>\n", | |
" <td>62</td>\n", | |
" <td>Amanda Mcmahan</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" <tr>\n", | |
" <th>4</th>\n", | |
" <td>28</td>\n", | |
" <td>Ann Rountree</td>\n", | |
" <td>[email protected]</td>\n", | |
" </tr>\n", | |
" </tbody>\n", | |
"</table>\n", | |
"</div>" | |
], | |
"text/plain": [ | |
" index NAME EMAIL\n", | |
"0 68 Albert Cunningham [email protected]\n", | |
"1 72 Allen Martinez [email protected]\n", | |
"2 73 Amalia Mouret [email protected]\n", | |
"3 62 Amanda Mcmahan [email protected]\n", | |
"4 28 Ann Rountree [email protected]" | |
] | |
}, | |
"execution_count": 8, | |
"metadata": {}, | |
"output_type": "execute_result" | |
} | |
], | |
"source": [ | |
"dffinal.reset_index().head()" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": [] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Django Shell-Plus", | |
"language": "python", | |
"name": "django_extensions" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 2 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython2", | |
"version": "2.7.12" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 2 | |
} |
Para transformar Query do Django em DataFrame:
df = pd.DataFrame(list(User.objects.all().values()))
Pra mostrar somente algumas colunas:
df[['id', 'email']]
Transformando todos os campos do DataFrame num jSON
df.T.apply(dict).tolist()
Renomeando colunas
df.rename(columns={'old_name': 'new_name'})
Selecionando as colunas de 10 em 10
df.iloc[:, :10]
com transposição
df.T.iloc[:10]
Novo df com algumas colunas.
new = old.filter(['A','B','D'], axis=1)
Como não inserir chaves com valor nulo no dicionário:
df.T.apply(lambda x: dict(x.dropna())).tolist()
Retornando os valores cujo tamanho da string seja maior que...
df[df['foo'].str.len() > 50]['foo']
Mostrando o tamanho de cada célula
df[df['foo'].str.len() > 50]['foo'].str.len()
Mostrando o tamanho de cada célula da coluna
df['foo_len'] = df['foo'].apply(len)
df[['foo_len', 'foo']]
Ou
df['foo'].str.len()
Suponha que você tenha Cliente
e Obra
.
Pegando o ID do Cliente que está em Obra e trocando pelo nome do Cliente que está no outro DataFrame.
# JSON do Cliente com IDCliente e Cliente
dict_cliente = df_cliente[['IDCliente', 'Cliente']].T.apply(dict).tolist()
[
{'IDCliente': 288, 'Cliente': 'Cliente Um'},
{'IDCliente': 1, 'Cliente': 'Cliente Dois'},
{'IDCliente': 959, 'Cliente': 'Cliente Três'},
]
Montando o dicionário que será usado como busca de cada Cliente a partir do seu ID.
_dict_cliente = {}
for item in dict_cliente:
_dict_cliente[item['IDCliente']] = item['Cliente']
_dict_cliente
{
288: 'Cliente Um',
1: 'Cliente Dois',
959: 'Cliente Três',
}
A partir desse dicionário fazemos a busca no outro DataFrame.
for row in df.itertuples():
nome_cliente = _dict_cliente.get(row.IDCliente)
print(row.IDCliente, nome_cliente)
288 Cliente Um
1 Cliente Dois
959 Cliente Três
Retornando o valor máximo agrupado por ano.
df.groupby(['Ano'])['NumeroOrcamento'].max()
df.reset_index()
Verificando data vazia:
for row in df.itertuples():
if row.DataOrcamento is pd.NaT:
print('Vazio')
else:
print(row.DataOrcamento)
Definindo vários fillna
diferentes por coluna:
values = {'last_name': '', 'occupation': '', 'age': 0}
df = df.fillna(value=values)
df.head()
Se tiver problema com liblzma
, faça um downgrade do Pandas para pandas==0.24.2
.
https://stackoverflow.com/a/57115325
Retorna o tamanho do maior objeto de cada coluna.
dict_sizes = {}
for col in df.columns:
try:
print(f'{col} max length: {df[col].map(len).max()}\n')
dict_sizes[col] = df[col].map(len).max()
except Exception as e:
raise e
dict_sizes
dtype example
df['estoque'] =df['estoque'].fillna(0).astype(int)
Pandas Dataframe df to Django
https://www.laurivan.com/save-pandas-dataframe-as-django-model/
Produto.objects.bulk_create(
Produto(**item) for item in df.to_dict('records')
)
Definindo os tipos das colunas com dtype
dict_types_annot = {
'produto': str,
'ncm': str,
'preco': float,
'estoque': 'Int64',
}
# Define os tipos das colunas
dff = df.astype(dict_types_annot, errors='ignore')
# Troca 'nan' por None e float por None.
dff = dff.replace({'nan': None, float('nan'): None})
dff.to_dict('records')
Produto.objects.bulk_create(
Produto(**item) for item in dff.to_dict('records')
)
Intersecção de dataframes
import pandas as pd
import numpy as np
import datetime
from random import randint
df1 = pd.DataFrame({
'letters': ['A', 'B', 'C', 'D', 'E', 'J', 'K', 'M'],
'B': np.random.randint(0, 10, 8),
})
df1
df2 = pd.DataFrame({
'letters': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'U', 'Z'],
'B': np.random.randint(0, 10, 26),
})
df2
# Retorna o que tem de comum nos dois dataframes.
pd.merge(df1, df2, how='inner', on='fruits')
# Retorna o que tem de comum, considerando o df1.
pd.merge(df1, df2, how='left', on='fruits')
# Retorna o que tem de comum, considerando o df2.
pd.merge(df1, df2, how='right', on='fruits')
Código que substitui da célula [6] em diante do
separe_email.ipynb
:Um detalhe é a falta de um índice único dos registros. Então, supondo o índice automático decorrente da importação do arquivo Excel como ID válido, esse ID é o usado no "join" (
merge
).