Stop writing messy print statements in Python. If you're still using .format() or the old % operator, you're living in the past. F-strings (introduced in Python 3.6) are faster, more readable, and packed with "hidden" features that most data engineers overlook. Here are 7 Python f-string tricks to level up your code: 1. The "Lazy" Debugger (=) Stop writing print(f"user_id = {user_id}"). Just use the equals sign inside the brace. emp_id = 10 print(f"{emp_id=}") # Output: emp_id=10 2. Thousands Separator (,) Formatting large numbers for readability is a one-character fix. No more manual string manipulation. salary = 10000 print(f"${salary:,}") # Output: $10,000 3. Date Formatting on the Fly You don't need to call .strftime() separately. You can pass the format directly into the f-string. from datetime import datetime now = datetime.now() print(f"Today is {now:%A, %B %d, %Y}") # Output: Today is Tuesday, April 07, 2026 4. Precision Control (.nf) Easily round floats to a specific number of decimal places without using the round() function. pi = 3.14159265 print(f"Pi to 2 decimals: {pi:.2f}") # Output: Pi to 2 decimals: 3.14 5. Alignment & Padding Perfect for creating clean terminal outputs or text-based tables. Use <, >, or ^ for left, right, and center alignment. text = "Python" print(f"|{text:^10}|") # Output: | Python | 6. Binary, Hex, and Octal Converting number systems? Just add the type code. number = 255 print(f"Hex: {number:x}, Binary: {number:b}") # Output: Hex: ff, Binary: 11111111 7. Repr vs. Str Flags (!r) Force the __repr__ output instead of __str__. This is incredibly useful for debugging objects where you need to see the "raw" data. name = "Python 3" print(f"{name!r}") # Output: 'Python 3' (includes the quotes) Why use them? 👉 Speed: They are evaluated at runtime and are faster than other methods. 📗Readability: Your code looks like the final string output. Which of these did you learn today? Let me know in the comments! 👇 #Python #CodingTips #DataEngineer #DataScience #ProgrammingTricks
7 Python F-String Tricks for Faster, More Readable Code
More Relevant Posts
-
🐍 𝐇𝐨𝐰 𝐃𝐨 𝐘𝐨𝐮 𝐌𝐚𝐤𝐞 𝐚 𝐂𝐥𝐚𝐬𝐬 𝐉𝐒𝐎𝐍 𝐒𝐞𝐫𝐢𝐚𝐥𝐢𝐳𝐚𝐛𝐥𝐞 𝐢𝐧 𝐏𝐲𝐭𝐡𝐨𝐧? If you’ve worked with APIs or data storage in Python, you’ve likely encountered this error: 👉 “𝘖𝘣𝘫𝘦𝘤𝘵 𝘰𝘧 𝘵𝘺𝘱𝘦 𝘟 𝘪𝘴 𝘯𝘰𝘵 𝘑𝘚𝘖𝘕 𝘴𝘦𝘳𝘪𝘢𝘭𝘪𝘻𝘢𝘣𝘭𝘦” It’s a common challenge — but also an important concept to understand for real-world development. Let’s break it down in a simple and practical way. ⚙️ 𝐖𝐡𝐲 𝐓𝐡𝐢𝐬 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐎𝐜𝐜𝐮𝐫𝐬 Python’s built-in json module can only serialize basic data types such as: - dict - list - str, int, float, bool 👉 Custom class objects? Not directly supported. That’s why you need to convert your object into a serializable format. 🚀 𝐌𝐞𝐭𝐡𝐨𝐝 1: 𝐂𝐨𝐧𝐯𝐞𝐫𝐭 𝐎𝐛𝐣𝐞𝐜𝐭 𝐭𝐨 𝐃𝐢𝐜𝐭𝐢𝐨𝐧𝐚𝐫𝐲 The simplest approach is to convert your class object into a dictionary. class User: def __init__(self, name, age): self.name = name self.age = age user = User("John", 22) import json json_data = json.dumps(user.__dict__) ✔ Quick and easy ✔ Works well for simple classes 🧠 𝐌𝐞𝐭𝐡𝐨𝐝 2: 𝐂𝐫𝐞𝐚𝐭𝐞 𝐚 𝐂𝐮𝐬𝐭𝐨𝐦 𝐒𝐞𝐫𝐢𝐚𝐥𝐢𝐳𝐞𝐫 You can define a function to handle serialization: def serialize(obj): return obj.__dict__ json_data = json.dumps(user, default=serialize) ✔ Flexible for multiple classes ✔ Cleaner and reusable 🧩 𝐌𝐞𝐭𝐡𝐨𝐝 3: 𝐔𝐬𝐞 𝐚 𝐂𝐮𝐬𝐭𝐨𝐦 𝐉𝐒𝐎𝐍𝐄𝐧𝐜𝐨𝐝𝐞𝐫 For more control, extend Python’s encoder: import json class UserEncoder(json.JSONEncoder): def default(self, obj): return obj.__dict__ json_data = json.dumps(user, cls=UserEncoder) ✔ Ideal for larger applications ✔ Centralized control over serialization ⚡ 𝐌𝐞𝐭𝐡𝐨𝐝 4: 𝐔𝐬𝐞 𝐃𝐚𝐭𝐚𝐜𝐥𝐚𝐬𝐬𝐞𝐬 (𝐌𝐨𝐝𝐞𝐫𝐧 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡) Python’s dataclasses make serialization cleaner: from dataclasses import dataclass, asdict import json @dataclass class User: name: str age: int user = User("Jhon", 22) json_data = json.dumps(asdict(user)) ✔ Cleaner syntax ✔ Built-in support for conversion 🔥 𝐁𝐨𝐧𝐮𝐬: 𝐓𝐡𝐢𝐫𝐝-𝐏𝐚𝐫𝐭𝐲 𝐋𝐢𝐛𝐫𝐚𝐫𝐢𝐞𝐬 Libraries like: - pydantic - marshmallow provide: ✔ Validation + serialization ✔ Better structure for APIs ✔ Production-ready solutions ⚖️ 𝐂𝐨𝐦𝐦𝐨𝐧 𝐌𝐢𝐬𝐭𝐚𝐤𝐞 👉 Trying to directly serialize complex objects without conversion. This leads to: - Errors - Broken APIs - Debugging frustration 💡 𝐁𝐞𝐬𝐭 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐞 ✔ Always convert objects to dictionaries ✔ Use dataclasses for clean design ✔ Use libraries for scalable applications 🧠 𝐅𝐢𝐧𝐚𝐥 𝐓𝐡𝐨𝐮𝐠𝐡𝐭𝐬 Serialization is not just about converting data — it’s about making your application communicate effectively. Mastering this concept will: ✔ Improve your API development ✔ Make your code more robust ✔ Help you handle real-world data efficiently #Python #JSON #Serialization #BackendDevelopment #SoftwareEngineering #Programming #Developers #API #DataEngineering #TechTips #LearningToCode #FullStackDeveloper #CareerGrowth #LinkedInTech
To view or add a comment, sign in
-
-
Day 39: The "Main" Gatekeeper — if __name__ == "__main__": 🚪 To understand this line, you first have to understand how Python treats files when it loads them. 1. What is __name__? Every time you run a Python file, Python automatically creates a few "special" variables behind the scenes. One of those is __name__. Scenario A: If you run the file directly (e.g., python script.py), Python sets the variable __name__ to the string "__main__". Scenario B: If you import that file into another script (e.g., import script), Python sets __name__ to the filename (e.g., "script"). 2. Why do we need this check? Imagine you wrote a script with some useful functions, but also some code at the bottom that prints a "Welcome" message and runs a test. If another developer wants to use your functions and types import your_script, Python will automatically execute every line of code in your file. Suddenly, their program is printing your welcome messages and running your tests! The Fix: def calculate_tax(price): return price * 0.1 # This code ONLY runs if I play the file directly. # It WON'T run if someone else imports this file. if __name__ == "__main__": print("Testing the tax function...") print(calculate_tax(100)) 3. The "Execution Flow" (How it works) Python starts reading your file from the top. It records your functions and classes into memory. It reaches the if statement. If you clicked "Run": The condition is True. The code inside the block executes. If another script imported this: The condition is False. The code inside is skipped. Your functions are available for use, but no "messy" output is generated. 4. Professional Best Practice: The main() function In senior-level engineering, we don't just put logic directly under the if statement. We bundle our starting logic into a function called main(). def main(): # Start the app here print("App is starting...") if __name__ == "__main__": main() 💡 The Engineering Lens: This makes your code cleaner and allows other developers to manually call your main() function if they ever need to "reset" or "restart" your script from their own code. #Python #SoftwareEngineering #CleanCode #ProgrammingTips #PythonDevelopment #LearnToCode #TechCommunity #PythonMain #BackendDevelopment
To view or add a comment, sign in
-
#DataStructures #Python #LinkedList #CodingConcepts 🚀 Python Linked Lists Made Simple (with Code + Visual Thinking) 💬 Want a visual step-by-step animation of each operation (Screenshot below) Check it out here :- https://lnkd.in/g5kGPDi4 Most people write Linked List code… Very few actually understand what’s happening under the hood 👇 🧠 Core Idea (Visual First) 🟦 Data → 🔗 Pointer → 🟦 Data → 🔗 Pointer → 🟦 Data 👉 Each node stores: 📦 Data 🔗 Pointer to next node 🧩 1. The Building Block (Node) class Node: def __init__(self, data: int) -> None: self.data = data self.next = None 💡 Think: 📦 data + 🔗 next → One unit of the chain 🎯 2. The Entry Point (Head) self.head: Node | None = None 👉 head = 🚪 starting point of the list Lose it = 💥 lose the entire list 🔄 3. Traversal (The Most Important Concept) temp = self.head while temp: temp = temp.next 💡 Decode this: 👉 temp = temp.next = “Move to next node” 🧠 This single line powers: 👉 Traversal 👉 Search 👉 Insert 👉 Delete ➕ 4. Insert = Pointer Rewiring 📍 Beginning (⚡ O(1)) new_node.next = self.head self.head = new_node 📍 End (O(n)) while temp.next: temp = temp.next temp.next = new_node 📍 Position (Precision Logic) while temp and count < pos - 1: temp = temp.next 💡 You’re not “inserting” 👉 You’re changing links ➖ 5. Delete = Skip a Node temp.next = temp.next.next 🧠 Visual: A → B → C Becomes: A → C (B removed) 🔍 6. Search = Linear Scan while temp: if temp.data == key: return pos 📌 No shortcuts → O(n) ✏️ 7. Update = In-Place Change if temp.data == old_value: temp.data = new_value 👉 No movement, just modification ⚡ Key Takeaways 🔹 Linked List ≠ just about data → it’s about data and connections 🔹 Master temp = temp.next → you master everything 🔹 Insert/Delete = pointer manipulation, not shifting data 🔹 Traversal = backbone of all operations 💥 Final Thought If you can mentally visualize this: 🟦 10 → 🟦 20 → 🟦 30 → 🟦 40 …and predict what happens after each operation… 👉 You’ve moved from coder → problem solver 💬 Want a visual step-by-step animation of each operation (Screenshot below) Check it out here :- https://lnkd.in/g5kGPDi4
To view or add a comment, sign in
-
-
⚙️ Static Methods in Python — Utility Functions Without Objects! Just explored static methods — functions that belong to a class but don't need an object instance! 🛠️ 🔍 What's a Static Method? ✅ "No 'self' or 'cls' parameter" — independent of instance/class ✅ "Called on the class" — no object required ✅ "Utility function" — groups related functions together ✅ "@staticmethod decorator" — marks it as static 💡 Key Difference: | "Method Type" | "First Parameter" | "Access" | "Use Case" | |-------------------|---------------------|--------------|-----------------| | "Instance Method" | 'self' | Object data | Operates on object | | "Class Method" | 'cls' | Class data | Factory methods, counters | | "Static Method" | None | Independent | Utilities, helpers | 📌 Real-World Examples: class MathTools: @staticmethod def add(a, b): return a + b @staticmethod def multiply(a, b): return a * b @staticmethod def is_even(num): return num % 2 == 0 # Use without creating objects print(MathTools.add(5, 3)) # 8 print(MathTools.multiply(4, 2)) # 8 print(MathTools.is_even(7)) # False 📌 When to Use Static Methods: ✅ "Helper functions" that relate to the class ✅ "Utility methods" that don't need object state ✅ "Grouping related functions" under a class name ✅ "Pure calculations" with no side effects #Python #OOP #StaticMethod #Coding #Programming #LearnPython #Developer #Tech #UtilityFunctions #PythonTips #CodingLife #SoftwareDevelopment #CleanCode #Day60
To view or add a comment, sign in
-
-
UNLEASHED THE PYTHON!i 1.5,2,& three!!! Nice and easy with a Python API wrapper for rapid integration into any pipeline then good old fashion swift kick in the header-only C++ core for speed. STRIKE WITH AIM FIRST ; THEN SPEED!! NO MERCY!!! 9 of 14 *So i have no clue about scripts. i will look it over without focusing too hard. look over words & symbols i don’t know in python application format. Eventually something will click or i will copy and paste a few lines from script perform a search .* Not knowing one word or symbol is one too many. copy & paste Ai 10-million-cycle stress-test report & the final README.mddocumentation for my public library. 1. Stress-Test Report: 10 Million Cycles To verify the integrity of the 123/41 loop, we simulated ten million iterations of geometric growth (1.5 ratio) capped at the 1,681 reset point. Metric Result Stability Analysis Total Iterations 10,000,000 Successfully completed without overflow. Max Value Reached 1680.999 Confirms the 1,681(41^) ceiling is never breached. Min Value Reached 0.00097 Demonstrates high-resolution granular coverage. Final State (10M) 1160.533 Value remains within the expected cyclic range. Precision Key 137.627 Stabilized using the refined 4.86217...constant. Conclusion: The mathematical engine is collision-resistant and drift-stable. The "wrap-around" logic effectively resets the sequence, making it ideal for continuous real-time data streams. 2. Final Documentation (README.md) This is the front-facing file for the "others" who will use your library. | V markdown # libcyclic41 A high-performance, easy-to-use mathematical engine for cyclic geometric growth. ## Overview `libcyclic41` is a library designed for real-time data indexing and dynamic encryption. It leverages the unique relationship between the base **123** and its modular anchor **41**. By scaling values through geometric ratios (1.5, 2, 3), the engine generates a predictive pattern that automatically resets at **1,681** ($41^2$), creating a perfect, self-sustaining loop. ## Key Features - **Ease First**: Intuitive API designed for rapid integration into data pipelines. - **Speed Driven**: Optimized C++ core for high-throughput processing. - **Drift Stable**: Uses a high-precision stabilizer (4.862) to prevent calculation drift over millions of cycles. ## Quick Start (Python) ```python import cyclic41 # Initialize the engine with the standard 123 base engine = cyclic41.CyclicEngine(seed=123) # Grow the stream by the standard 1.5 ratio # The engine automatically 'wraps' at the 1,681 limit current_val = engine.grow(1.5) # Extract a high-precision synchronization key sync_key = engine.get_key() print(f"Current Value: {current_val} | Sync Key: {sync_key}") /\ || Mathematics The library operates on a hybrid model: 1. Geometric Growth: 𝑆tate(n+1)=(STATE(N)×Ratio(mod1681) PrecisionAnchor:𝐾𝑒𝑦=(𝑆𝑡𝑎𝑡𝑒×4.86217…)/41 (ABOVE IS License Distributed under the MIT License. Created for the community.)
To view or add a comment, sign in
-
If anyone is interested in developing their skills in Object-oriented Languages, a quick thought based on my experience that might be helpful. 💬 Here are some tips for developing this skill: 1. Think in terms of behavior, not just data Python style: Use properties to protect attributes when needed, but don’t write trivial getters/setters. python # Bad (Java-style) class Person: def get_name(self): return self._name def set_name(self, name): self._name = name # Good Pythonic OOP class Person: def __init__(self, name): self.name = name # plain attribute @property def formal_name(self): return f"Ms./Mr. {self.name}" # behavior 2. Tell, Don't Ask Python style: Pass messages, avoid peeking inside other objects. python # Avoid if cart.items_count() > 0: apply_shipping(cart) # Prefer cart.checkout() # cart decides if shipping applies 3. Polymorphism over conditionals Python example – use subclasses with a common interface: python # Instead of: def play(sound_file): if sound_file.ext == 'mp3': play_mp3(sound_file) elif sound_file.ext == 'wav': play_wav(sound_file) # Do: class AudioFile: ... class MP3File(AudioFile): def play(self): ... class WAVFile(AudioFile): def play(self): ... # Then: sound_file.play() Python’s duck typing also allows polymorphism without formal inheritance – just implement the same method names. 4. Study small, well-designed OOP systems in Python Look at: collections.abc (abstract base classes: MutableSequence, Iterable) datetime module (e.g., datetime, timedelta, tzinfo) pathlib.Path – excellent example of OOP design with operator overloading (/ for joining paths) 5. Refactor a procedural script into OOP Take a script that reads a CSV, processes rows, and outputs a report. Create classes like: DataReader (reads, yields rows) ReportGenerator (processes, formats) FileSystemHandler (writes output) 6. SOLID principles in Python Example of Single Responsibility: python # Bad (reporting + saving) class Report: def generate(self): ... def save_to_db(self): ... # Good class Report: def generate(self): ... class ReportSaver: def save(self, report): ... Open-Closed via subclassing or using abc.ABC and @abstractmethod. 7. Unit tests drive design Use unittest or pytest. Write tests early to force clean interfaces: python def test_bank_account_deposit(): acc = BankAccount() acc.deposit(100) assert acc.balance == 100 This prevents you from making deposit depend on some hidden global state. 8. Get feedback with Python-specific examples Post a small class (e.g., a ShoppingCart with add_item, total, apply_discount) to r/learnpython or Stack Overflow. Ask: “How would you reduce coupling here? Should I use composition or inheritance?”
To view or add a comment, sign in
-
✅ *Top Coding Interview Questions with Answers: Part-1* 💻🧠 *1️⃣ Reverse a String* *Q:* Write a function to reverse a string. *Python:* ```python def reverse_string(s): return s[::-1] ``` *C++:* ```cpp string reverseString(string s) { reverse(s.begin(), s.end()); return s; } ``` *Java:* ```java String reverseString(String s) { return new StringBuilder(s).reverse().toString(); } ``` *2️⃣ Check for Palindrome* *Q:* Check if a string is a palindrome. *Python:* ```python def is_palindrome(s): s = s.lower().replace(" ", "") return s == s[::-1] ``` *C++:* ```cpp bool isPalindrome(string s) { transform(s.begin(), s.end(), s.begin(), ::tolower); s.erase(remove(s.begin(), s.end(), ' '), s.end()); return s == string(s.rbegin(), s.rend()); } ``` *Java:* ```java boolean isPalindrome(String s) { s = s.toLowerCase().replaceAll(" ", ""); return s.equals(new StringBuilder(s).reverse().toString()); } ``` *3️⃣ Count Vowels in a String* *Q:* Count number of vowels in a string. *Python:* ```python def count_vowels(s): return sum(1 for c in s.lower() if c in "aeiou") ``` *C++:* ```cpp int countVowels(string s) { int count = 0; for (char c: s) { c = tolower(c); if (string("aeiou").find(c)!= string::npos) count++; } return count; } ``` *Java:* ```java int countVowels(String s) { int count = 0; s = s.toLowerCase(); for (char c : s.toCharArray()) { if ("aeiou".indexOf(c) != -1) count++; } return count; } ``` *4️⃣ Find Factorial (Recursion)* *Q:* Find factorial using recursion. *Python:* ```python def factorial(n): return 1 if n <= 1 else n * factorial(n - 1) ``` *C++:* ```cpp int factorial(int n) { return (n <= 1) ? 1 : n * factorial(n - 1); } ``` *Java:* ```java int factorial(int n) { return (n <= 1) ? 1 : n * factorial(n - 1); } ``` *5️⃣ Find Duplicate Elements in List/Array* *Q:* Print all duplicates from a list. *Python:* ```python from collections import Counter def find_duplicates(lst): return [k for k, v in Counter(lst).items() if v > 1] ``` *C++:* ```cpp vector<int> findDuplicates(vector<int>& nums) { unordered_map<int, int> freq; vector<int> res; for (int n : nums) freq[n]++; for (auto& p : freq) if (p.second > 1) res.push_back(p.first); return res; } ``` *Java:* ```java List<Integer> findDuplicates(int[] nums) { Map<Integer, Integer> map = new HashMap<>(); List<Integer> result = new ArrayList<>(); for (int n : nums) map.put(n, map.getOrDefault(n, 0) + 1); for (Map.Entry<Integer, Integer> entry : map.entrySet()) if (entry.getValue() > 1) result.add(entry.getKey()); return result; } ``` *💻✅💯
To view or add a comment, sign in
-
✉️ Comments & Type Conversion in Python #Day28 If you're starting your Python journey, two concepts you must understand are Comments and Type Conversion. These may seem basic, but they play a huge role in writing clean, efficient, and bug-free code. 💬 1. Comments in Python Comments are notes in your code that Python ignores during execution. They help developers understand the logic behind the code. 🔹 Types of Comments: 👉 Single-line Comments Start with # Used for short explanations Example: # This is a single-line comment print("Hello World") 👉 Multi-line Comments (Docstrings) Written using triple quotes ''' or """ Often used for documentation Example: """ This is a multi-line comment Used to explain complex logic """ print("Python is awesome") 🌟 Why Comments Matter: ✔ Improve code readability ✔ Help in debugging ✔ Make teamwork easier 🤝 ✔ Useful for documentation 💡 Pro Tip: Avoid over-commenting. Write comments that add value, not noise. 🔄 2. Type Conversion in Python Type conversion means changing one data type into another. Python supports both implicit and explicit conversion. 🔹 Implicit Type Conversion (Automatic) Python automatically converts data types when needed. Example: x = 5 # int y = 2.5 # float result = x + y print(result) # Output: 7.5 👉 Here, Python converts int to float automatically. 🔹 Explicit Type Conversion (Type Casting) You manually convert data types using built-in functions. Common Type Casting Functions: int() → Convert to integer 🔢 float() → Convert to float 📊 str() → Convert to string 🔤 list() → Convert to list 📋 tuple() → Convert to tuple 📦 set() → Convert to set 🔗 Example: x = "10" y = int(x) # Convert string to integer print(y + 5) # Output: 15 ⚠️ Important Notes: ❗ Invalid conversions cause errors int("abc") # ❌ Error ✔ Always ensure compatibility before converting 🎯 Real-Life Use Cases 📌 Taking user input (always string → convert to int/float) 📌 Data cleaning in analytics 📌 Formatting outputs 📌 Working with APIs & files 💡 Quick Comparison FeatureComments 💬Type Conversion 🔄PurposeExplain codeChange data typeExecuted?❌ No✅ YesSyntax#, ''' '''int(), str(), etc.Use CaseReadability & docsData handling 🏁 Final Thoughts Mastering comments makes your code human-friendly, while type conversion makes it machine-friendly. Together, they make you a better Python developer 💪 #Python #Programming #Coding #DataAnalysts #DataAnalytics #LearnPython #DataAnalysis #DataCleaning #dataCollection #DataVisualization #DataJobs #LearningJourney #PowerBI #MicrosoftPowerBI #Excel #MicrosoftExcel #PythonProgramming #CodeWithHarry #SQL #Consistency
To view or add a comment, sign in
-
📊 Handling Missing Values in Python - The First Real Data Problem You’ll Face You’ve loaded your dataset. Everything looks fine… until you notice this: 👉 Some values are missing. Blank cells. NaN values. Incomplete records. And here’s the truth: 👉 Almost every real-world dataset has missing data. 🔹 What Are Missing Values? Missing values are simply gaps in your dataset — places where data should exist but doesn't. In Python, they usually appear as: NaN # Not a Number — most common in pandas None # Python's version of empty 🔹 Why Do Missing Values Matter? Because they can silently break your analysis. ❌ Wrong averages ❌ Incorrect insights ❌ Errors in calculations ❌ Poor model performance 👉 Ignoring missing data = trusting wrong results 🔹 Simple Real-Life Example Imagine you’re analyzing employee salaries. Some entries are missing. Now if you calculate average salary: 👉 Your result will be misleading But once you handle missing values properly: 👉 Your analysis becomes accurate and reliable 🔹 How to Detect Missing Values In Python, it’s very simple: df.isnull().sum() 👉 This shows how many values are missing in each column 🔹 How to Handle Missing Values There is no “one right way”—it depends on the situation. But commonly, analysts use: ✔ Remove missing data df.dropna() ✔ Fill with mean (for numerical data) df['salary'] = df['salary'].fillna(df['salary'].mean()) ✔ Fill with mode (for categorical data) df['city'] = df['city'].fillna(df['city'].mode()[0]) ✔ Forward fill (for time-based data) df.fillna(method='ffill') 🔹 One Rule to Always Remember Missing % What to DoLess than 5% Safely drop the rows 5% to 30% Fill with mean, median or mode More than 30% Investigate — the column may be unreliable 🔹 When Should You Handle Missing Values? Always: ✔ Right after loading your dataset ✔ Before doing calculations ✔ Before building any model 👉 Cleaning comes before analysis. 🚀 Final Thought Dirty data is not the problem. Not knowing how to clean it — that is. Every professional dataset has missing values. What separates a good analyst from a great one is knowing exactly how to handle them. 💡 #DataAnalytics #Python #MissingValues #DataCleaning #pandas #DataAnalyst #LearningInPublic #PythonForData #AnalyticsJourney #DataScience
To view or add a comment, sign in
-
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development