Pandas/ Pytorch/ Python Flashcards

(5 cards)

1
Q

Updating rows in DataFrame → to avoid err

A

.loc for updating specific rows

```python
df.loc[rows, ‘column’] = value

- `rows` → row indices to update
- `'column'` → column to change
- `value` → new value

**Example:**

```python
df['Split'] = 'Test'
train_idx = [0,2,4]
df.loc[train_idx, 'Split'] = 'Train'

Result:

  text  Split
0    a  Train
1    b   Test
2    c  Train
3    d   Test
4    e  Train

Why .loc: safely updates the DataFrame in place; avoids warnings from chained indexing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

abstract method in Python

A

Define in parent class, not implement and must be override from subclass

from abc import ABC, abstractmethod

class Animal(ABC):
    
    @abstractmethod
    def make_sound(self):
        pass   # No implementation

class Dog(Animal):
    
    def make_sound(self):
        return "Woof!"

class Cat(Animal):
    
    def make_sound(self):
        return "Meow"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does .view(-1, 1) change a tensor’s shape from and to?

A

It changes a 1D tensor of shape [N] into a 2D tensor of shape [N, 1].

import torch

x = torch.tensor([1, 2, 3, 4, 5, 6])
print(x.shape)   # torch.Size([6])

y = x.view(-1, 1)
print(y)
print(y.shape)   # torch.Size([6, 1])
tensor([[1],
        [2],
        [3],
        [4],
        [5],
        [6]])
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly