Home Artificial Intelligence 4 Pandas One-Liners That Solve Particular Tasks Efficiently

4 Pandas One-Liners That Solve Particular Tasks Efficiently

0
4 Pandas One-Liners That Solve Particular Tasks Efficiently

Complex tasks accomplished in a fast and straightforward way

Towards Data Science
Photo by Tom Bradley on Unsplash

Third-party libraries are created and developed in response to a necessity. Nobody sits down and says “I’m gonna create a tool and wait for circumstances to arise through which others need it”. As an alternative, they realize an issue and consider an answer to assist solve it. That’s how tools are created.

The identical goes for adding latest features to existing tools. How well and quickly latest features are added will depend on the recognition of the tool and the team behind it.

Pandas, needless to say, has a highly lively community that keeps Pandas as one of the vital popular data evaluation and cleansing libraries in the info science ecosystem.

Pandas has functions to unravel very specific issues and use cases. These will need to have been demanded from the community who’re actively using it.

In this text, I’ll share 4 operations you could do in a single line of code with Pandas. These helped me solve particular tasks efficiently and surprised me in an excellent way.

1. Create a dictionary from an inventory

I actually have an inventory of things and I would like to see the distribution of them. To be more specific, I would like to see the unique values together with their variety of occurrences within the list.

A Python dictionary is a fantastic solution to store data on this format. The items can be the dictionary keys and variety of occurrences can be the values.

Because of the value_counts and to_dict functions, this task could be accomplished in a single line of code.

Here is an easy example to exhibit this case:

import pandas as pd

grades = ["A", "A", "B", "B", "A", "C", "A", "B", "C", "A"]

pd.Series(grades).value_counts().to_dict()

# output
{'A': 5, 'B': 3, 'C': 2}

We first convert the list to a Pandas Series, which is the one-dimensional data structure of Pandas. Then, we apply the value_counts function to get the unique values with their frequency within the Series. Finally, we convert the output to a dictionary.

2. Create a DataFrame from a JSON file

LEAVE A REPLY

Please enter your comment!
Please enter your name here