Skip to content

Commit f406371

Browse files
Merge branch 'main' into copilot/update-documentation-for-users
2 parents d2d0979 + 23d0583 commit f406371

File tree

6 files changed

+493
-1
lines changed

6 files changed

+493
-1
lines changed

bin/concept-of-the-week.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
content/kotlin/concepts/classes/classes.md
1+
content/uiux/concepts/quantitative-research/quantitative-research.md
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
---
2+
Title: 'byteswap()'
3+
Description: 'Swaps the byte order of each element in a NumPy ndarray.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Array'
9+
- 'Data'
10+
- 'NumPy'
11+
CatalogContent:
12+
- 'learn-python-3'
13+
- 'paths/data-science'
14+
---
15+
16+
The **`byteswap()`** method reverses the byte order of every element in a NumPy array. This is used when converting data between systems with different endianness (byte-ordering conventions). The operation either returns a new array or modifies the original one in place when `inplace=True`.
17+
18+
## Syntax
19+
20+
```pseudo
21+
ndarray.byteswap(inplace=False)
22+
```
23+
24+
**Parameters:**
25+
26+
- `inplace` (optional): When set to `True`, the byte order of the existing array is swapped in place. When `False`, a new array with swapped bytes is returned.
27+
28+
**Return value:**
29+
30+
Returns a new ndarray with swapped byte order, unless `inplace=True`, in which case the original array is modified and returned.
31+
32+
## Example 1
33+
34+
In this example, the array's byte order is swapped to convert the data into the opposite endianness:
35+
36+
```py
37+
import numpy as np
38+
39+
arr = np.array([1, 256, 1024], dtype=np.int32)
40+
41+
print("Original array:")
42+
print(arr)
43+
print("Original dtype:", arr.dtype)
44+
45+
swapped = arr.byteswap()
46+
47+
print("\nAfter byteswap():")
48+
print(swapped)
49+
print("Swapped dtype:", swapped.dtype)
50+
```
51+
52+
The output of this code is:
53+
54+
```shell
55+
Original array:
56+
[ 1 256 1024]
57+
Original dtype: int32
58+
59+
After byteswap():
60+
[16777216 65536 262144]
61+
Swapped dtype: int32
62+
```
63+
64+
## Example 2
65+
66+
This example demonstrates `byteswap(inplace=True)` and shows how the original data is altered directly:
67+
68+
```py
69+
import numpy as np
70+
71+
arr = np.array([100, 200, 300], dtype=np.int32)
72+
73+
print("Before inplace byteswap:", arr)
74+
75+
arr.byteswap(inplace=True)
76+
77+
print("After inplace byteswap:", arr)
78+
```
79+
80+
The output of this code is:
81+
82+
```shell
83+
Before inplace byteswap: [100 200 300]
84+
After inplace byteswap: [1677721600 -939524096 738263040]
85+
```
86+
87+
## Codebyte Example
88+
89+
Use the codebyte below to inspect how `byteswap()` affects a 2-D array and observe the internal memory representation change:
90+
91+
```codebyte/python
92+
import numpy as np
93+
94+
matrix = np.array([[1, 2], [3, 4]], dtype=np.int16)
95+
96+
print("Original:")
97+
print(matrix)
98+
99+
swapped = matrix.byteswap()
100+
101+
print("\nByteswapped:")
102+
print(swapped)
103+
```
104+
105+
## Frequently Asked Questions
106+
107+
### 1. What is the function of byteswap() in Python?
108+
109+
The `byteswap()` method reverses the byte order of every element in a NumPy array. It is commonly used when preparing data for systems with different endianness or when interpreting binary data from external sources.
110+
111+
### 2. What are bytes and bytearrays in Python?
112+
113+
A `bytes` object in Python is an immutable sequence of byte values, while a bytearray is a mutable version of the same concept. Both store raw binary data and are often used for file handling, networking, and low-level memory operations.
114+
115+
### 3. How to shuffle a NumPy ndarray?
116+
117+
A NumPy array can be shuffled using `np.random.shuffle()` for in-place row-wise shuffling or `np.random.permutation()` to return a shuffled copy. These functions randomize the order of elements while preserving the array’s structure.
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
---
2+
Title: 'size()'
3+
Description: 'Returns a Series containing the size (row count) of each group.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Data Structures'
9+
- 'Pandas'
10+
CatalogContent:
11+
- 'learn-python-3'
12+
- 'paths/data-science'
13+
---
14+
15+
The **`size()`** method in pandas returns the number of rows or elements in each group created by the `groupby()` [function](https://www.codecademy.com/resources/docs/pandas/built-in-functions). It provides a quick way to determine group sizes without applying an aggregation function.
16+
17+
## Syntax
18+
19+
```pseudo
20+
DataFrameGroupBy.size()
21+
```
22+
23+
**Parameters:**
24+
25+
The `size()` method doesn't take any parameters.
26+
27+
**Return value:**
28+
29+
The `size()` method returns a Series containing the size (row count) of each group created by `groupby()`.
30+
31+
## Example 1: Counting Rows by Group
32+
33+
In this example, a [DataFrame](https://www.codecademy.com/resources/docs/pandas/dataframe) of employees is grouped by their department, and `size()` counts how many employees belong to each department:
34+
35+
```py
36+
import pandas as pd
37+
38+
data = {
39+
'Department': ['HR', 'IT', 'HR', 'Finance', 'IT', 'Finance'],
40+
'Employee': ['John', 'Sara', 'Mike', 'Anna', 'Tom', 'Chris']
41+
}
42+
df = pd.DataFrame(data)
43+
44+
group_sizes = df.groupby('Department').size()
45+
print(group_sizes)
46+
```
47+
48+
The output of this code is:
49+
50+
```shell
51+
Department
52+
Finance 2
53+
HR 2
54+
IT 2
55+
dtype: int64
56+
```
57+
58+
## Example 2: Using Multiple Grouping Columns
59+
60+
In this example, `size()` counts the number of members in each combination of team and shift within a dataset:
61+
62+
```py
63+
import pandas as pd
64+
65+
data = {
66+
'Team': ['A', 'A', 'B', 'B', 'B', 'C'],
67+
'Shift': ['Day', 'Night', 'Day', 'Night', 'Day', 'Day'],
68+
'Name': ['John', 'Sara', 'Mike', 'Anna', 'Tom', 'Chris']
69+
}
70+
df = pd.DataFrame(data)
71+
72+
group_sizes = df.groupby(['Team', 'Shift']).size()
73+
print(group_sizes)
74+
```
75+
76+
The output of this code is:
77+
78+
```shell
79+
Team Shift
80+
A Day 1
81+
Night 1
82+
B Day 2
83+
Night 1
84+
C Day 1
85+
dtype: int64
86+
```
87+
88+
## Codebyte Example: Counting Transactions Per Product
89+
90+
In this example, `size()` is used to count how many sales transactions occurred for each product in a store dataset:
91+
92+
```codebyte/python
93+
import pandas as pd
94+
95+
sales = pd.DataFrame({
96+
'Product': ['Apple', 'Banana', 'Apple', 'Orange', 'Banana', 'Banana', 'Apple'],
97+
'Customer': ['A', 'B', 'C', 'A', 'D', 'E', 'F']
98+
})
99+
100+
counts = sales.groupby('Product').size()
101+
print(counts)
102+
```
103+
104+
## Frequently Asked Questions
105+
106+
### 1. What is the pandas `groupby().size()` method?
107+
108+
`groupby().size()` returns the number of rows in each group created by `groupby()`.
109+
110+
### 2. What is the purpose of `groupby()` in pandas?
111+
112+
`groupby()` splits data into groups based on selected column values to enable aggregation and summarization.
113+
114+
### 3. What does `NaN` stand for in pandas?
115+
116+
`NaN` stands for Not a Number and indicates missing or undefined data.
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
---
2+
Title: '.log2()'
3+
Description: 'Computes the base-2 logarithm of each element in the input tensor and returns a new tensor with the results.'
4+
Subjects:
5+
- 'Code Foundations'
6+
- 'Computer Science'
7+
Tags:
8+
- 'Elements'
9+
- 'Methods'
10+
- 'PyTorch'
11+
- 'Tensors'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/data-science'
15+
---
16+
17+
The **`.log2()`** method in PyTorch returns a new [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors) by computing the logarithm base 2 of each element in the input tensor. This operation is useful in numerous data-science and machine-learning workflows where values are interpreted on a log scale (e.g., information theory, binary magnitude comparisons).
18+
19+
## Syntax
20+
21+
```pseudo
22+
torch.log2(input, *, out=None) → Tensor
23+
```
24+
25+
**Parameters:**
26+
27+
- `input` (Tensor): The tensor whose elements are to be transformed by base-2 logarithm.
28+
- `out` (Tensor, optional): A tensor to store the output; must have the same shape as input if provided.
29+
30+
**Return value:**
31+
32+
Returns a new tensor of the same shape as `input` where each element is `log₂(input[i])`.
33+
34+
## Example 1: Basic Usage of `.log2()`
35+
36+
In this example, the base-2 logarithm is computed for a tensor containing powers of 2:
37+
38+
```py
39+
import torch
40+
41+
# Define a tensor
42+
input_tensor = torch.tensor([2.0, 4.0, 8.0, 16.0, 32.0])
43+
44+
# Compute base-2 logarithm
45+
output_tensor = torch.log2(input_tensor)
46+
47+
print(output_tensor)
48+
```
49+
50+
The output of this code is:
51+
52+
```shell
53+
tensor([1., 2., 3., 4., 5.])
54+
```
55+
56+
## Example 2: Applying `.log2()` on Random Values
57+
58+
In this example, a tensor with random positive values is transformed using base-2 logarithm to analyze data on a log scale:
59+
60+
```py
61+
import torch
62+
63+
# Generate a tensor of random positive values
64+
data = torch.rand(5) * 10 + 1
65+
66+
# Apply log2 transformation
67+
log_tensor = torch.log2(data)
68+
69+
print(data)
70+
print(log_tensor)
71+
```
72+
73+
The output of this code is:
74+
75+
```shell
76+
tensor([10.5500, 9.2777, 10.9371, 1.3551, 5.2609])
77+
tensor([3.3992, 3.2138, 3.4512, 0.4384, 2.3953])
78+
```

0 commit comments

Comments
 (0)