☰
Current Page
Main Menu
Home
Home
Editing 10 Python Functions Every Data Scientist Must Memorize
Edit
Preview
H1
H2
H3
default
Set your preferred keybinding
default
vim
emacs
markdown
Set this page's format to
AsciiDoc
Creole
Markdown
MediaWiki
Org-mode
Plain Text
RDoc
Textile
Rendering unavailable for
BibTeX
Pod
reStructuredText
Help 1
Help 1
Help 1
Help 2
Help 3
Help 4
Help 5
Help 6
Help 7
Help 8
Autosaved text is available. Click the button to restore it.
Restore Text
https://medium.com/@Behavior2020/10-python-functions-every-data-scientist-must-memorize-60821960e2ad # 10 Python Functions Every Data Scientist Must Memorize | by Nick Mishkin | Medium Save time toggling between ChatGPT and Google with these ten python functions -----------------------------------------------------------------------------  [Nick Mishkin](https://medium.com/@Behavior2020) Photo by [Vitaly Gariev](https://unsplash.com/@silverkblack?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com/?utm_source=medium&utm_medium=referral) It’s tempting to turn to Google and ChatGPT every time you need a python function. Toggling back and forth, however, is time-consuming and energy-draining. According to professors Meyer, Evans, and Rubinstein each “task switch” can lead to a [40% loss in productivity](https://www.apa.org/topics/research/multitasking#:~:text=Thus%2C%20multitasking%20may%20seem%20efficient,percent%20of%20someone's%20productive%20time.). After experiencing too much brain drain from toggling, I decided to memorize these ten Python functions, and my programming abilities soared. In this article, you will learn the ten functions that boosted my coding competence. I’ve included examples for each one to guide you through some of the nuances. The examples are based on randomly generated sales data. > This article was inspired by [Tech with Tim](https://www.youtube.com/watch?v=kGcUtckifXc). 1\. Print Function ------------------ The `print()` function is one of the most basic yet powerful tools in Python. It allows you to display results. Notice you can play with the “sep ” parameter. ``` def display_sales_info(product, sales, revenue): print('Product', product, sep=': ') print('Total Sales', sales, sep=': ') print('Total Revenue', revenue, sep=': ') display_sales_info('Laptop', 1500, '3000 USD') # Output """ Product: Laptop Total Sales: 1500 Total Revenue: 3000 USD ``` 2\. Help Function ----------------- The `help()` function is invaluable when you need to understand how a particular function or module works. It provides the documentation for the specified function or module. ``` def calculate_discounted_price(price, discount): """ Calculate the discounted price of a product. price: original price of the product discount: discount percentage to be applied returns: float """ return price * (1 - discount / 100) # Example of using the help function help(calculate_discounted_price) # Output """ Returns function docstring ``` 3\. Range Function ------------------ The `range()` function generates a sequence of numbers, which is useful for iterating over with loops. ``` def generate_sales_days(start_day, end_day): return list(range(start_day, end_day + 1)) print(generate_sales_days(1, 7)) # Generates days of the week # Output """ [1, 2, 3, 4, 5, 6, 7] ``` 4\. Map Function ---------------- The `map()` function applies a given function to all items in an input list. ``` def apply_discount(prices, discount): return list(map(lambda x: x * (1 - discount / 100), prices)) print(apply_discount([100, 200, 300, 400, 500], 10)) # Apply a 10% discount # Output """ [90.0, 180.0, 270.0, 360.0, 450.0] ``` 5\. Filter Function ------------------- The `filter()` function constructs an iterator from elements of an iterable for which a function returns true. ``` def filter_high_sales(sales, threshold): return list(filter(lambda x: x > threshold, sales)) print(filter_high_sales([100, 200, 50, 300, 150], 150)) # Filter sales greater than 150 # Output """ [200, 300] ``` 6\. Sorted Function ------------------- The `sorted()` function returns a sorted list from the items in an iterable. Use reverse=True to reverse the order. ``` def sort_sales_data_by_sales(data): return sorted(data, key=lambda x: x['Sales']) sales_data = [ {'Product': 'Laptop', 'Sales': 150}, {'Product': 'Mouse', 'Sales': 300}, {'Product': 'Keyboard', 'Sales': 200}, ] print(sort_sales_data_by_sales(sales_data)) # Output """ [{'Product': 'Laptop', 'Sales': 150}, {'Product': 'Keyboard', 'Sales': 200}, {'Product': 'Mouse', 'Sales': 300}] ``` 7\. Enumerate Function ---------------------- The `enumerate()` function adds a counter to an iterable and returns it in a form of an enumerate object. ``` def list_products_with_index(products): for index, product in enumerate(products): print(f"{index + 1}. {product}") list_products_with_index(['Laptop', 'Mouse', 'Keyboard']) # Output """ 1. Laptop 2. Mouse 3. Keyboard ``` 8\. Zip Function ---------------- The `zip()` function returns an iterator of tuples, where the first item in each passed iterator is paired together, and then the second item in each passed iterator is paired together, etc. ``` def combine_sales_data(products, sales): return list(zip(products, sales)) print(combine_sales_data(['Laptop', 'Mouse', 'Keyboard'], [150, 300, 200])) # Output """ [('Laptop', 150), ('Mouse', 300), ('Keyboard', 200)] ``` 9\. Open Function ----------------- The `open()` function opens a file, returning a file object that allows you to read from or write to the file. ``` def write_sales_to_file(filename, content): """Writes content into file""" with open(filename, "w") as file: file.write(content) def read_sales_file(filename): """Reads content in file only""" with open(filename, "r") as file: return file.read() def append_sales_to_file(filename, content): """Appends new content to original content""" with open(filename, "a") as file: file.write(content) write_sales_to_file("sales.txt", "Product: Laptop\nSales: 150") print(read_sales_file("sales.txt")) append_sales_to_file("sales.txt", "\nProduct: Mouse\nSales: 300") print(read_sales_file("sales.txt")) # Output """ Product: Laptop Sales: 150 Product: Mouse Sales: 300 ``` 10 Sum Function: ---------------- The `sum()` function sums the items of an iterable from left to right and returns the total. You can also set the “start” parameter to add to a number. ``` def calculate_total_sales(sales): return sum(sales) print(calculate_total_sales([150, 300, 200])) # Output """ 650 ``` Honorable Mentions ------------------ * `dict.get()` — a dictionary method that retrieves the value associated with a specified key, returning a default value if the key is not found. * `requests.get( )` — sends a GET request to a specified URL and returns a Response object containing the server's response data. * `response.json()` — parses the JSON content of a Response object and returns it as a Python dictionary. * `json.load()` — reads a JSON formatted file and converts its content into a corresponding Python dictionary or list. * `df.to_csv()` — writes the contents of a DataFrame to a CSV file, with various options for specifying the file path, delimiter, and other formatting parameters. * `join()` — concatenates the elements of an iterable (such as a list or tuple) into a single string, with a specified separator between each element. Concluding Remarks ------------------ Memorizing these ten Python functions will enhance your ability to tackle diverse programming tasks. By mastering these functions, you eliminate the need to constantly toggle between Google and ChatGPT, which not only saves time but also prevents productivity loss. Integrating these functions seamlessly into your workflow allows you to write data science scripts at lightning speed. Embrace the power of these tools and watch your productivity skyrocket. Happy coding! If you have any questions or just want to connect, feel free to reach out on [LinkedIn](https://www.linkedin.com/in/nickmishkin/).
Uploading file...
Edit message:
Cancel