Python/10 Python Functions Every Data Scientist Must Memorize.md
... ...
@@ -0,0 +1,234 @@
1
+https://medium.com/@Behavior2020/10-python-functions-every-data-scientist-must-memorize-60821960e2ad
2
+
3
+# 10 Python Functions Every Data Scientist Must Memorize | by Nick Mishkin | Medium
4
+Save time toggling between ChatGPT and Google with these ten python functions
5
+-----------------------------------------------------------------------------
6
+![Nick Mishkin](https://miro.medium.com/v2/resize:fill:88:88/1*ZMBahNvURx7iOcSW0_Bgxw.jpeg)
7
+[Nick Mishkin](https://medium.com/@Behavior2020)
8
+
9
+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)
10
+
11
+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.
12
+
13
+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.
14
+
15
+> This article was inspired by [Tech with Tim](https://www.youtube.com/watch?v=kGcUtckifXc).
16
+
17
+1\. Print Function
18
+------------------
19
+
20
+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.
21
+
22
+```
23
+def display_sales_info(product, sales, revenue):
24
+ print('Product', product, sep=': ')
25
+ print('Total Sales', sales, sep=': ')
26
+ print('Total Revenue', revenue, sep=': ')
27
+display_sales_info('Laptop', 1500, '3000 USD')
28
+
29
+# Output
30
+"""
31
+Product: Laptop
32
+Total Sales: 1500
33
+Total Revenue: 3000 USD
34
+```
35
+
36
+
37
+2\. Help Function
38
+-----------------
39
+
40
+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.
41
+
42
+```
43
+def calculate_discounted_price(price, discount):
44
+""" Calculate the discounted price of a product.
45
+price: original price of the product
46
+discount: discount percentage to be applied returns: float
47
+"""
48
+return price * (1 - discount / 100)
49
+
50
+# Example of using the help function
51
+help(calculate_discounted_price)
52
+
53
+# Output
54
+""" Returns function docstring
55
+```
56
+
57
+
58
+3\. Range Function
59
+------------------
60
+
61
+The `range()` function generates a sequence of numbers, which is useful for iterating over with loops.
62
+
63
+```
64
+def generate_sales_days(start_day, end_day):
65
+ return list(range(start_day, end_day + 1))
66
+
67
+print(generate_sales_days(1, 7)) # Generates days of the week
68
+
69
+# Output
70
+""" [1, 2, 3, 4, 5, 6, 7]
71
+```
72
+
73
+
74
+4\. Map Function
75
+----------------
76
+
77
+The `map()` function applies a given function to all items in an input list.
78
+
79
+```
80
+def apply_discount(prices, discount):
81
+ return list(map(lambda x: x * (1 - discount / 100), prices))
82
+
83
+print(apply_discount([100, 200, 300, 400, 500], 10)) # Apply a 10% discount
84
+
85
+# Output
86
+""" [90.0, 180.0, 270.0, 360.0, 450.0]
87
+```
88
+
89
+
90
+5\. Filter Function
91
+-------------------
92
+
93
+The `filter()` function constructs an iterator from elements of an iterable for which a function returns true.
94
+
95
+```
96
+def filter_high_sales(sales, threshold):
97
+ return list(filter(lambda x: x > threshold, sales))
98
+
99
+print(filter_high_sales([100, 200, 50, 300, 150], 150)) # Filter sales greater than 150
100
+
101
+# Output
102
+""" [200, 300]
103
+```
104
+
105
+
106
+6\. Sorted Function
107
+-------------------
108
+
109
+The `sorted()` function returns a sorted list from the items in an iterable. Use reverse=True to reverse the order.
110
+
111
+```
112
+def sort_sales_data_by_sales(data):
113
+ return sorted(data, key=lambda x: x['Sales'])
114
+
115
+sales_data = [
116
+ {'Product': 'Laptop', 'Sales': 150},
117
+ {'Product': 'Mouse', 'Sales': 300},
118
+ {'Product': 'Keyboard', 'Sales': 200},
119
+]
120
+
121
+print(sort_sales_data_by_sales(sales_data))
122
+
123
+# Output
124
+"""
125
+[{'Product': 'Laptop', 'Sales': 150},
126
+{'Product': 'Keyboard', 'Sales': 200},
127
+{'Product': 'Mouse', 'Sales': 300}]
128
+```
129
+
130
+
131
+7\. Enumerate Function
132
+----------------------
133
+
134
+The `enumerate()` function adds a counter to an iterable and returns it in a form of an enumerate object.
135
+
136
+```
137
+def list_products_with_index(products):
138
+ for index, product in enumerate(products):
139
+ print(f"{index + 1}. {product}")
140
+
141
+list_products_with_index(['Laptop', 'Mouse', 'Keyboard'])
142
+
143
+# Output
144
+"""
145
+1. Laptop
146
+2. Mouse
147
+3. Keyboard
148
+```
149
+
150
+
151
+8\. Zip Function
152
+----------------
153
+
154
+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.
155
+
156
+```
157
+def combine_sales_data(products, sales):
158
+ return list(zip(products, sales))
159
+
160
+print(combine_sales_data(['Laptop', 'Mouse', 'Keyboard'], [150, 300, 200]))
161
+
162
+# Output
163
+""" [('Laptop', 150), ('Mouse', 300), ('Keyboard', 200)]
164
+```
165
+
166
+
167
+9\. Open Function
168
+-----------------
169
+
170
+The `open()` function opens a file, returning a file object that allows you to read from or write to the file.
171
+
172
+```
173
+def write_sales_to_file(filename, content):
174
+ """Writes content into file"""
175
+ with open(filename, "w") as file:
176
+ file.write(content)
177
+
178
+def read_sales_file(filename):
179
+ """Reads content in file only"""
180
+ with open(filename, "r") as file:
181
+ return file.read()
182
+
183
+def append_sales_to_file(filename, content):
184
+ """Appends new content to original content"""
185
+ with open(filename, "a") as file:
186
+ file.write(content)
187
+
188
+write_sales_to_file("sales.txt", "Product: Laptop\nSales: 150")
189
+print(read_sales_file("sales.txt"))
190
+
191
+append_sales_to_file("sales.txt", "\nProduct: Mouse\nSales: 300")
192
+print(read_sales_file("sales.txt"))
193
+
194
+# Output
195
+"""
196
+Product: Laptop
197
+Sales: 150
198
+Product: Mouse
199
+Sales: 300
200
+```
201
+
202
+
203
+10 Sum Function:
204
+----------------
205
+
206
+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.
207
+
208
+```
209
+def calculate_total_sales(sales):
210
+ return sum(sales)
211
+
212
+print(calculate_total_sales([150, 300, 200]))
213
+
214
+# Output
215
+""" 650
216
+```
217
+
218
+
219
+Honorable Mentions
220
+------------------
221
+
222
+* `dict.get()` — a dictionary method that retrieves the value associated with a specified key, returning a default value if the key is not found.
223
+* `requests.get( )` — sends a GET request to a specified URL and returns a Response object containing the server's response data.
224
+* `response.json()` — parses the JSON content of a Response object and returns it as a Python dictionary.
225
+* `json.load()` — reads a JSON formatted file and converts its content into a corresponding Python dictionary or list.
226
+* `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.
227
+* `join()` — concatenates the elements of an iterable (such as a list or tuple) into a single string, with a specified separator between each element.
228
+
229
+Concluding Remarks
230
+------------------
231
+
232
+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!
233
+
234
+If you have any questions or just want to connect, feel free to reach out on [LinkedIn](https://www.linkedin.com/in/nickmishkin/).
... ...
\ No newline at end of file