PyData Careers
20.8K subscribers
205 photos
4 videos
26 files
351 links
Python Data Science jobs, interview tips, and career insights for aspiring professionals.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Python OOP Tip: Inheritance Basics! 🚀

Inheritance allows a new class (child) to acquire properties and methods from an existing class (parent), promoting code reuse and establishing an "is-a" relationship.

class Vehicle:
def init(self, brand):
self.brand = brand

def description(self):
return f"This is a {self.brand} vehicle."

class Car(Vehicle): # Car inherits from Vehicle
def init(self, brand, model):
super().init(brand) # Call parent's constructor
self.model = model

def drive(self):
return f"The {self.brand} {self.model} is driving."

my_car = Car("Toyota", "Camry")
print(my_car.description())
print(my_car.drive())

Key Takeaway: Use super().init() in a child class to properly initialize parent attributes when overriding the constructor.

#Python #OOP #Inheritance #PythonTips #Programming
---
By: @DataScienceQ
2
Pandas Python Tip: Custom Column Operations with apply()! 🚀

The df.apply() method is powerful for applying a function along an axis of the DataFrame (rows or columns), especially useful for custom transformations on columns or rows.

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Score': [85, 92, 78]}
df = pd.DataFrame(data)

Example: Create a new column 'Grade' based on 'Score'

def assign_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
else:
return 'C'

df['Grade'] = df['Score'].apply(assign_grade)
print(df)

You can also use lambda functions for simpler operations

df['Score_Double'] = df['Score'].apply(lambda x: x * 2)
print(df)

Key Takeaway: df.apply() (especially on a Series) is excellent for element-wise custom logic, often more readable than complex vectorized operations for specific tasks.

#Pandas #Python #DataScience #DataManipulation #PythonTips
---
By: @DataScienceQ
1
🚀 NumPy Tip: Boolean Indexing (Masking) 🚀

Ever need to filter your arrays based on a condition? NumPy's Boolean Indexing, also known as masking, is your go-to! It allows you to select elements that satisfy a specific condition.

import numpy as np

Create a sample NumPy array

data = np.array([12, 5, 20, 8, 35, 15, 30])

Create a boolean mask: True where value is > 10, False otherwise

mask = data > 10
print("Boolean Mask:", mask)

Apply the mask to the array to filter elements

filtered_data = data[mask]
print("Filtered Data (values > 10):", filtered_data)

You can also combine the condition and indexing directly

even_numbers = data[data % 2 == 0]
print("Even Numbers:", even_numbers)

Explanation:
A boolean array (the mask) is created by applying a condition to your original array. When this mask is used for indexing, NumPy returns a new array containing only the elements where the mask was True. Simple, powerful, and efficient!

#NumPy #PythonTips #DataScience #ArrayMasking #Python #Programming

---
By: @DataScienceQ
💡 collections.namedtuple for structured data: Create simple, immutable data structures without boilerplate.

from collections import namedtuple

Define a simple Point structure

Point = namedtuple('Point', ['x', 'y'])

Create instances

p1 = Point(10, 20)
p2 = Point(x=30, y=40)

print(f"Point 1: x={p1.x}, y={p1.y}")
print(f"Point 2: {p2[0]}, {p2[1]}") # Access by index

It's still a tuple!

print(f"Is p1 a tuple? {isinstance(p1, tuple)}")

Example with a Person

Person = namedtuple('Person', 'name age city')
person = Person('Alice', 30, 'New York')
print(f"Person: {person.name} is {person.age} from {person.city}")

#PythonTips #DataStructures #collections #namedtuple #Python

---
By: @DataScienceQ
1
🧠 Quiz: Which Pythonic approach is generally preferred for creating a new list by transforming elements from an existing list?

A) Using a for loop with list.append()
B) Using a list comprehension
C) Using the map() function followed by list()
D) Using a while loop with list.append()

Correct answer: B

Explanation: List comprehensions are often more concise, readable, and generally more performant than explicit for loops or map() for creating new lists based on existing iterables. They encapsulate the iteration and creation logic cleanly.

#PythonTips #PythonicCode #ListComprehensions

---
By: @DataScienceQ
1
🧠 Quiz: Which of the following is the most Pythonic and efficient way to iterate through a list my_list and access both each item and its corresponding index?

A) i = 0; while i < len(my_list): item = my_list[i]; i += 1
B) for index, item in enumerate(my_list):
C) for index in range(len(my_list)): item = my_list[index]
D) for item in my_list: index = my_list.index(item)

Correct answer: B

Explanation: The enumerate() function is specifically designed to provide both the index and the item while iterating over a sequence, making the code cleaner, more readable, and generally more efficient than manual indexing or while loops. Option D is inefficient as list.index(item) scans the list for each item, especially if duplicates exist.

#PythonTips #Pythonic #Programming

━━━━━━━━━━━━━━━
By: @DataScienceQ
💡 Python Conditionals: if, elif, and else

The if-elif-else structure allows your program to execute different code blocks based on a series of conditions. It evaluates them sequentially:

if: The first condition to check. If it's True, its code block runs, and the entire structure is exited.
elif: (short for "else if") If the preceding if (or elif) was False, this condition is checked. You can have multiple elif blocks.
else: This is an optional final block. Its code runs only if all preceding if and elif conditions were False.

This provides a clear and efficient way to handle multiple mutually exclusive scenarios.

# A program to categorize a number
number = 75

if number < 0:
category = "Negative"
elif number == 0:
category = "Zero"
elif 0 < number <= 50:
category = "Small Positive (1-50)"
elif 50 < number <= 100:
category = "Medium Positive (51-100)"
else:
category = "Large Positive (>100)"

print(f"The number {number} is in the category: {category}")
# Output: The number 75 is in the category: Medium Positive (51-100)


Code explanation: The script evaluates the variable number. It first checks if it's negative, then if it's zero. After that, it checks two positive ranges using elif. Since 75 is greater than 50 and less than or equal to 100, the condition 50 < number <= 100 is met, the category is set to "Medium Positive", and the final else block is skipped.

#Python #ControlFlow #IfStatement #PythonTips #ProgrammingLogic

━━━━━━━━━━━━━━━
By: @DataScienceQ
Python tip:

itertools.zip_longest pairs elements from multiple iterables, but unlike the built-in zip(), it continues until the longest iterable is exhausted, padding shorter ones with a specified fillvalue.

While zip() truncates its output to the length of the shortest input, zip_longest() ensures no data is lost from longer inputs by substituting None (or a custom value) for missing items.

Example👇
>>> import itertools
>>> students = ['Alice', 'Bob', 'Charlie', 'David']
>>> scores = [88, 92, 75]
>>> grades = list(itertools.zip_longest(students, scores, fillvalue='Absent'))
grades
[('Alice', 88), ('Bob', 92), ('Charlie', 75), ('David', 'Absent')]

#Python #ProgrammingTips #Itertools #PythonTips #CleanCode

━━━━━━━━━━━━━━━
By: @DataScienceQ
1
Python Clean Code:

The collections.defaultdict simplifies dictionary creation by providing a default value for keys that have not been set yet, eliminating the need for manual existence checks.

Instead of writing if key not in my_dict: before initializing a value (like a list or a counter), defaultdict handles this logic automatically upon the first access of a missing key. This prevents KeyError and makes grouping and counting code significantly cleaner.

Example👇
>>> from collections import defaultdict
>>>
>>> # Cluttered way with a standard dict
>>> data = [('fruit', 'apple'), ('veg', 'carrot'), ('fruit', 'banana')]
>>> grouped_data = {}
>>> for category, item in data:
... if category not in grouped_data:
... grouped_data[category] = []
... grouped_data[category].append(item)
...
>>> # Clean way with defaultdict
>>> clean_grouped_data = defaultdict(list)
>>> for category, item in data:
... clean_grouped_data[category].append(item)
...
>>> clean_grouped_data
defaultdict(<class 'list'>, {'fruit': ['apple', 'banana'], 'veg': ['carrot']})

#Python #CleanCode #PythonTips #DataStructures #CodeReadability

━━━━━━━━━━━━━━━
By: @DataScienceQ
The Walrus Operator := (Assignment Expressions)

Introduced in Python 3.8, the "walrus operator" := allows you to assign a value to a variable as part of a larger expression. It's a powerful tool for writing more concise and readable code, especially in while loops and comprehensions.

It solves the common problem where you need to compute a value, check it, and then use it again.

---

#### The Old Way: Repetitive Code

Consider a loop that repeatedly prompts a user for input and stops when the user enters "quit".

# We have to get the input once before the loop,
# and then again inside the loop.
command = input("Enter command: ")

while command != "quit":
print(f"Executing: {command}")
command = input("Enter command: ")

print("Exiting program.")

Notice how input("Enter command: ") is written twice.

---

#### The Pythonic Way: Using the Walrus Operator :=

The walrus operator lets you capture the value and test it in a single, elegant line.

while (command := input("Enter command: ")) != "quit":
print(f"Executing: {command}")

print("Exiting program.")

Here, (command := input(...)) does two things:
• Calls input() and assigns its value to the command variable.
• The entire expression evaluates to that same value, which is then compared to "quit".

This eliminates redundant code, making your logic cleaner and more direct.

#Python #PythonTips #PythonTricks #WalrusOperator #Python3 #CleanCode #Programming #Developer #CodingTips

━━━━━━━━━━━━━━━
By: @DataScienceQ
2