In this article, I will discuss 3 important features of Python that comes in handy for a data scientist and saves a lot of time. Let’s begin without wasting any time.
List & Dict Comprehensions are a very powerful tool in Python that comes in handy to make lists. It saves time, easy in syntax, and makes the logic easier as compared to making a list using normal Python for-loop.
Basically, these are used instead of an explicit for-loop with simple logic inside it that appends or does something with a list or dictionary. These are single line and makes the code more readable.
List Comprehensions
Will will see a normal python example first and then will see it’s equivalent using list comprehensions.
Scenario
Let’s say we have a simple dataframe in Pandas with students results in 3 subjects.
In [1]: results = [[10,8,7],[5,4,3],[8,6,9]]
In [2]: results = pd.DataFrame(results, columns=['Maths','English','Science'])
And if we print it,
In [5]: results
Out[5]:
Maths English Science
0 10 8 7
1 5 4 3
2 8 6 9
Now let’s say we want to make a list with maximum marks of each subject, i.e., that list should be equal to [10,8,9] because these are maximum marks of each subject.
Python Code
In [7]: maxlist = []
In [8]: for i in results:
…: maxlist.append(max(results[i]))
#2020 jul tutorials # overviews #pandas #programming #python #tips