Colunas calculadas no SharePoint | Uma visão geral
Descubra a importância das colunas calculadas no SharePoint e como elas podem realizar cálculos automáticos e obtenção de dados em suas listas.
Como um cientista de dados trabalhando com Python, você provavelmente já se deparou com a biblioteca NumPy . É um dos pacotes fundamentais para computação científica em Python .
Com sua capacidade de executar operações de alto desempenho em arrays multidimensionais, o NumPy é uma ferramenta essencial para qualquer um que se aprofunde em ciência de dados ou computação numérica em Python.
Uma folha de dicas do NumPy pode ser um excelente recurso para ajudar a guiar sua jornada nesta biblioteca Python. Uma folha de dicas abrangente ajudará você a navegar pelos recursos do NumPy e rapidamente se tornar proficiente em usá-lo para várias tarefas!
Além disso, lembre-se de que o NumPy está no centro de bibliotecas importantes, como Pandas, SciPy, sci-kit-learn e outros pacotes Python.
Ao dominar seus fundamentos com a ajuda da folha de dicas Python NumPy , você estará melhor equipado para trabalhar com essas bibliotecas. Você também aprimorará suas habilidades em lidar com estruturas de dados e cálculos complexos.
Você é antiquado (como nós) e deseja baixar e potencialmente imprimir sua folha de dicas?
Role para baixo para fazer isso.
Índice
Noções básicas do NumPy
Nesta seção, abordaremos o básico do NumPy, com foco na instalação do NumPy, criação de array, atributos de array e tipos de dados. Esses conceitos fornecerão uma base sólida para entender e utilizar efetivamente o NumPy em seus projetos de ciência de dados Python.
1. Instalando e importando o NumPy
Você pode instalar o NumPy a partir da linha de comando usando o comando abaixo:
pip install numpy
Depois de instalado, importe-o para o seu código.
import numpy as np
Lembre-se de que você pode usar qualquer outro nome além de np . No entanto, np é a convenção de importação padrão do NumPy usada pela maioria dos desenvolvedores e cientistas de dados.
2. Criação de Matriz
Criar arrays no NumPy é simples e direto. Você pode criar arrays a partir de listas ou tuplas usando a função numpy.array() :
import numpy as np
a = np.array([1, 2, 3]) # Creates a 1D array
b = np.array([(1, 2, 3), (4, 5, 6)]) # Creates a 2D array
Você também pode gerar matrizes de formas e valores específicos usando várias funções:
np.zeros() : Cria uma matriz preenchida com zeros
np.ones() : Cria um array preenchido com uns
np.identity() : Cria uma matriz de matriz de identidade.
np.empty() : Cria uma matriz sem inicializar seus elementos para qualquer valor específico
np.arange() : Cria uma matriz com valores regularmente espaçados entre um valor inicial e final
np.linspace() : Cria uma matriz com um número especificado de valores uniformemente espaçados entre um valor inicial e final
Nota: Você não pode gerar uma matriz vazia no NumPy. Cada array NumPy tem um tamanho fixo e imutável e cada elemento do array deve ser preenchido quando o array é criado.
A função np.empty() cria a forma de array necessária e a preenche com valores aleatórios. O método padrão cria uma matriz de flutuações aleatórias.
Você pode criar um tipo de dados de matriz diferente usando o parâmetro dtype .
3. Atributos da matriz
As matrizes NumPy têm vários atributos que fornecem informações úteis sobre a matriz. Vejamos alguns deles:
ndarray.shape: Retorna as dimensões do array como uma tupla (linhas, colunas)
ndarray.ndim: Retorna o número de dimensões no array
ndarray.size: Retorna o número total de elementos no array
ndarray.dtype: Retorna o tipo de dado dos elementos do array
Para acessar esses atributos, use a notação de ponto, assim:
a = np.array([(1, 2, 3), (4, 5, 6)])
#Print out the array shape
print(a.shape) # Output: (2, 3)
4. Tipos de dados
O NumPy fornece vários tipos de dados para armazenar dados em arrays, como integer, string, float, boolean e complex. Por padrão, o NumPy tenta deduzir o tipo de dados com base nos elementos de entrada.
No entanto, você também pode especificar explicitamente o tipo de dados usando a palavra-chave dtype . Por exemplo:
import numpy as np
a = np.array([1, 2, 3], dtype=float) # Creates an array of floats
Os tipos de dados NumPy comuns incluem:
np.int32 : inteiro de 32 bits
np.int64: inteiro de 64 bits
np.float32: 32-bit floating-point number
np.float64: 64-bit floating-point number
np.complex: Complex number, represented by two 64-bit floating-point numbers
You can also convert arrays from one data type to another. In this example, here’s how we can convert the Integer array a into a Boolean array arr using the np.array() method.
From the example, we can see the array() method converts the array elements into boolean values. These boolean values then form the new NumPy array arr.
Understanding these basic concepts of NumPy will allow you to effectively work with arrays and perform a variety of mathematical NumPy operations. For example, you can check out our video on how to transform and code addresses In Python.
In it, we used Python Pandas and NumPy data types to geocode home addresses.
Array Manipulation
In this section, you will learn about various array shape manipulation techniques in NumPy. We will discuss reshaping, concatenation, copying, splitting, adding/removing elements, indexing, and slicing.
These techniques are crucial for effectively working with array data in your data science projects.
Let’s dive into each sub-section.
1. Reshaping
Reshaping an array in NumPy is a common task you’ll perform. You might need to change the shape of your array to match the requirements of a function or an algorithm.
To reshape an array, use the reshape() function:
arr = np.array([1, 2, 3, 4, 5, 6])
new_arr = arr.reshape(2, 3)
This will convert your one-dimensional array into a two-dimensional array with 2 rows and 3 columns.
Note: Make sure the new shape you provide has the same size (number of array elements) as the original array.
2. Copying
You can copy the elements in one NumPy array to another using the copy() method. You should note that using the assignment operator ‘=’ creates a shallow copy.
#Creating a shallow copy of a NumPy array
a = np.array([9, 6, 12, 16, 20])
b = a
b[0] = 19
print(a) #Output:[19, 6, 12, 16, 20]
print(b) #Output:[19, 6, 12, 16, 20]
The new array only references the old array in the system’s memory. They contain the same elements and they are not independent of each other.
By using the deep copy, you create a new NumPy array that contains the same data as the old one while being independent of it.
#Creating a deep copy of a NumPy array
a = np.array([9, 6, 12, 16, 20])
b = np.copy(a)
b[0] = 19
print(a) #Output:[9, 6, 12, 16, 20]
print(b) #Output:[19, 6, 12, 16, 20]
3. Concatenation
Occasionally, you may need to merge two arrays into a single one. In NumPy, you can use the concatenate() function to join arrays along an existing axis:
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = np.concatenate((arr1, arr2))
This combines arr1 and arr2 into a single array. Keep in mind that the arrays being concatenated should have the same shape, except along the specified axis.
4. Splitting
Splitting is the opposite of concatenation. You can divide an array into smaller sub-arrays using the split() function:
arr = np.array([1, 2, 3, 4, 5, 6])
result = np.split(arr, 3)
This splits the array into 3 equal-sized sub-arrays. Ensure that the number of splits you specify can evenly divide the size of the array along the given axis.
5. Adding/Removing Elements
Adding or removing elements in a NumPy array can be achieved using the append() and delete() functions. You can use the former to append values to the end of the array while the latter deletes the element at a specified index.
Here’s an example:
arr = np.array([1, 2, 3])
arr = np.append(arr, [4, 5, 6]) # Appends values to the end of the array
arr = np.delete(arr, 0) # Removes the array element on index 0
Keep in mind that NumPy arrays have a fixed size. When using append() or delete(), a new array is created, and the original one is not modified.
6. Indexing
You can perform indexing operations on NumPy arrays the same way you’d do them on Python lists or tuples. Let’s look at how you can access or change array elements in a given array.
arr = np.array([1, 2, 3])
#Returns the array element on index 1
element_2 = b[1]
#Change the array element on index 0
arr[0]= 89
7. Slicing
You can also slice NumPy arrays to extract or view a section of the data the same way you’d do Python lists or sets. Let’s take a look at an example below:
arr1 = np.array([1, 2, 3, 4, 5, 6, 7])
arr2 = np.array([(1, 2, 3, 6, 0), (4, 5, 6, 11, 13)])
# To return the first 3 elements of arr1
print(arr1[0:3]) #Output: [1, 2, 3]
# To return the second row in arr2
b = arr2[1, : ].copy() #Output: [4, 5, 6, 11, 13]
Note: Slicing creates a shallow copy that still references the main array. So, any change you make to the sliced data will be applied to the main array and vice versa.
To avoid this, you can use the copy() method to create a deep, independent copy.
Elementary Functions
In this section, you’ll learn about different elementary functions in NumPy, which will ease your data analysis tasks. We’ll cover arithmetic operations, trigonometry, and exponents and logarithms.
1. Arithmetic Operations
NumPy offers various math operations on arrays that make them simple and efficient to work with. array mathematics vector math
Some of the operations are:
Addition: numpy.add(x1, x2)
Subtraction: numpy.subtract(x1, x2)
Multiplication: numpy.multiply(x1, x2)
Division: numpy.divide(x1, x2)
Modulus: numpy.mod(x1, x2)
Power: numpy.power(x1, x2)
Square root: numpy.sqrt(x)
Note: When using these operations, the two arrays must be the same shape. If not, you’ll run into errors.
There is an exception for certain arrays thanks to a NumPy feature called broadcasting. We’ll cover that in a later section.
You can perform these operations element-wise on the arrays, which makes them highly efficient for large-scale data manipulation.
2. Trigonometry
Trigonometric functions play a significant role in various mathematical and scientific computations. NumPy provides a wide range of trigonometric functions.
Some of the essential functions are:
Sine: numpy.sin(x)
Cosine: numpy.cos(x)
Tangent: numpy.tan(x)
Arcsine: numpy.arcsin(x)
Arccosine: numpy.arccos(x)
Arctangent: numpy.arctan(x)
These functions work seamlessly with arrays, making it easier for you to perform vectorized computations on large datasets.
3. Exponents and Logarithms
Exponents and logarithms are crucial for various numerical operations. NumPy provides an extensive collection of functions for dealing with exponents and logarithms.
Some of the primary functions are:
Exponential: numpy.exp(x)
Logarithm(base e): numpy.log(x)
Logarithm(base 10): numpy.log10(x)
Logarithm(base 2): numpy.log2(x)
Utilizing these functions, you can quickly perform complex mathematical operations on each element in the array. This makes your data analysis tasks more accessible and efficient.
Array Analysis
In this section, we will discuss various techniques to analyze arrays and array elements in NumPy. Some of the key features we will cover include aggregate functions, statistical functions, searching, and sorting.
1. Aggregate Functions
NumPy provides several aggregate functions that allow you to perform operations on arrays, such as summing all their elements, finding the minimum or maximum value, and more:
sum: np.sum(your_array) – Calculate the sum of all the elements in the array.
min: np.min(your_array) – Find the minimum array element.
max: np.max(your_array) – Find the maximum array element.
mean: np.mean(your_array) – Calculate the mean of the values in the array.
median: np.median(your_array) – Find the median of the values in the array.
2. Statistical Functions
NumPy also has a variety of statistical functions to help you analyze data:
std: np.std(your_array) – Calculate the standard deviation of the values in the array.
var: np.var(your_array) – Calculate the variance of the values in the array.
corrcoef: np.corrcoef(your_array) – Calculate the correlation coefficient of the array.
3. Searching
Searching in NumPy arrays can be done using various methods:
argmin: np.argmin(your_array) – Find the index of the minimum array element.
argmax: np.argmax(your_array) – Encontre o índice do elemento máximo da matriz.
where: np.where(condição) – Retorna os índices dos elementos no array que satisfazem a condição dada.
4. Classificação
Você pode classificar os elementos em sua matriz usando as seguintes funções:
sort : np.sort(your_array) – Classifica os elementos no array em ordem crescente.
argsort: np.argsort(your_array) – Retorna os índices que classificariam o array.
Com essas funções e técnicas, você pode analisar e manipular convenientemente suas matrizes NumPy para descobrir informações valiosas e apoiar seus esforços de análise de dados.
Funções avançadas
Nesta seção, exploraremos algumas funções avançadas do NumPy para ajudá-lo a trabalhar com mais eficiência com seus dados. Abordaremos as funções Broadcasting e Linear Algebra.
1. Radiodifusão
A transmissão é um recurso poderoso do NumPy que permite executar operações em matrizes com diferentes formas e tamanhos. Ele funciona expandindo automaticamente as dimensões da matriz menor para corresponder à matriz maior, facilitando a execução de operações elementares.
Aqui está um exemplo:
import numpy as np
A = np.array([1, 2, 3])
B = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
C = A + B
Neste exemplo, a matriz 1D A é transmitida para corresponder à forma da matriz 2D B, permitindo a adição de elementos.
Lembre-se destas regras ao trabalhar com transmissão:
As dimensões dos arrays devem ser compatíveis (ou o mesmo tamanho ou um deles é 1).
A difusão é aplicada a partir das dimensões à direita e trabalha em direção às dimensões principais.
2. Álgebra Linear
O NumPy fornece várias funções de álgebra linear que podem ser úteis ao trabalhar com matrizes multidimensionais. Algumas dessas funções incluem:
np.dot(A, B): Calcula o produto escalar de duas matrizes.
np.linalg.inv(A) : Calcula o inverso de uma matriz quadrada.
np.linalg.eig(A) : Calcula os autovalores e autovetores de uma matriz quadrada.
np.linalg.solve(A, B): Resolve um sistema linear de equações, onde A é a matriz de coeficientes e B é a matriz de constantes.
Lembre-se de sempre verificar se suas matrizes são compatíveis antes de realizar essas operações.
Entrada e saída
Nesta seção, exploraremos como salvar e carregar arrays, bem como ler e gravar arquivos usando o NumPy.
1. Salvando e carregando matrizes
To save an array, you can use NumPy’s np.save() function. This function takes the filename and the array as its two main arguments.
import numpy as np
arr = np.array([1, 2, 3])
np.save('my_array.npy', arr)
To load the saved array, use the np.load() function, providing the filename as the argument.
loaded_array = np.load('my_array.npy')
print(loaded_array)
# Output: array([1, 2, 3])
You can also save and load multiple arrays using the np.save() and np.load() functions.
2. Reading and Writing to Text Files
NumPy provides functions to read and write text files with arrays, such as np.loadtxt() and np.savetxt(). You can use these functions to save and load data from file formats like a txt or CSV file.
Para ler um arquivo de texto em um array, use a função np.loadtxt() . Ele usa o nome do arquivo como argumento principal e também oferece suporte a argumentos opcionais para especificar o delimitador, dtype e muito mais.
arr_from_txt = np.loadtxt('data.txt', delimiter=',')
print(arr_from_txt)
Para ler os dados de um arquivo CSV, você também pode usar a função np.loadtxt() . No entanto, certifique-se de que o delimitador esteja sempre definido como vírgula, “ , “.
Para gravar uma matriz em um arquivo de texto, use a função np.savetxt() . Essa função usa o nome do arquivo e a matriz como seus dois argumentos principais, seguidos por argumentos opcionais, como delimitador e cabeçalho.
arr_to_txt = np.array([[1, 2, 3], [4, 5, 6]])
np.savetxt('output_data.txt', arr_to_txt, delimiter=',')
Essas funções de entrada e saída permitem que você trabalhe com eficiência com matrizes e arquivos de texto em suas tarefas de processamento e manipulação de dados usando o NumPy.
Baixe sua folha de dicas abaixo
Download da folha de truques Numpy
Pensamentos finais
Bem, isso é tudo que você precisa saber para começar a usar a biblioteca Numpy Python! Você também pode usar a folha de dicas Python Numpy como uma referência útil ao trabalhar com a biblioteca.
Para recursos mais avançados, você pode conferir a documentação do NumPy . Você também pode conferir esta divertida Folha de dicas do Python que reunimos para desenvolvedores novos e experientes.
Boa sorte!
Descubra a importância das colunas calculadas no SharePoint e como elas podem realizar cálculos automáticos e obtenção de dados em suas listas.
Descubra todos os atributos pré-atentivos e saiba como isso pode impactar significativamente seu relatório do LuckyTemplates
Aprenda a contar o número total de dias em que você não tinha estoque por meio dessa técnica eficaz de gerenciamento de inventário do LuckyTemplates.
Saiba mais sobre as exibições de gerenciamento dinâmico (DMV) no DAX Studio e como usá-las para carregar conjuntos de dados diretamente no LuckyTemplates.
Este tutorial irá discutir sobre Variáveis e Expressões dentro do Editor do Power Query, destacando a importância de variáveis M e sua sintaxe.
Aprenda a calcular a diferença em dias entre compras usando DAX no LuckyTemplates com este guia completo.
Calcular uma média no LuckyTemplates envolve técnicas DAX para obter dados precisos em relatórios de negócios.
O que é self em Python: exemplos do mundo real
Você aprenderá como salvar e carregar objetos de um arquivo .rds no R. Este blog também abordará como importar objetos do R para o LuckyTemplates.
Neste tutorial de linguagem de codificação DAX, aprenda como usar a função GENERATE e como alterar um título de medida dinamicamente.