## Posts

Showing posts with the label Python

### What Is REDUCE In Python

Before jumping on to what is reduce, let’s have a quick look at the lines  below :  import operator sum = 0 for n in [1,2,3]: sum = sum + n print ( sum ) You got it right. Here we are taking a collection having three numbers and summing them up. As such, there is nothing wrong with this code but, of course there is a big room for optimization with respect to the number of lines of code we have written, just go get summation. Now the question is, how can we optimize? How can we reduce the number of lines and achieve the same result? Well, the answer is reduce function. What is reduce? Reduce is a function in Python provided by functools . This function takes a collection of values, performs some operation by calling a function and then returns a single value as an output. For example, you can give multiple values as input and perform mathematical calculations on them, you can perform operations on multiple strings, etc. Ways to use reduce There are two ways you can use reduce: Way 1

### How To Give Name To A Size Column In Python

It is quite common to use size() in Python. size() function gives you a total number of elements. Now, if it is that easy and straight forward, then why am I writing about it? Isn't it? Well, calculating the size or getting the output of the size() function is very straight forward, but when it comes to labeling this value, things become more complicated. Let's understand this with the help of an example. Input Data Here is how our sample data looks like. It is in the form of CSV: Scenario Explained The idea is to group data based on 2 columns named 'type_school' and 'interest' and then show their item count in a separate column. Here is the sample code to achieve this: import pandas as pd df = pd . read_csv ( 'data.csv' ) data = df . groupby ( [ 'type_school' , 'interest' ] ) data [ 'size' ] = data . size ( ) print ( data ) Python Copy The above code looks all good but you will end up seeing an error in it's execu

### Getting The Terminal Size In Python

Many times our output doesn’t get fit into the terminal of default size. In that case we have to pull it accordingly and make the size as per our need. Image: Akshay Chauhan on Unsplash In this article, I’ll show you those few lines of Python code using which you can get the size of your terminal programmatically.  Now, before resizing our output we need to know, how to read the terminal size. There are possibly many ways to get the terminal size, i.e. reading environment variables, making low level system calls, etc. In this article, I’ll show you one of the easiest and simplest way to get the terminal size. import os s = os . get_terminal_size ( ) print ( s . columns , s . lines ) Python Copy You can also watch the video recording of this article on my YouTube channel  named Shweta Lodha .