Checking if a number is prime in Python

A pretty simple and concise brute-force solution to check whether a number N is prime: simply check if there is any divisor of N from 2 up to the square root of N (see why here if interested). The following code is compatible with both Python 2 and Python 3: And here’s a simpler Python 3 only … Read more

Convert pandas data frame to series

It’s not smart enough to realize it’s still a “vector” in math terms. Say rather that it’s smart enough to recognize a difference in dimensionality. 🙂 I think the simplest thing you can do is select that row positionally using iloc, which gives you a Series with the columns as the new index and the values … Read more

How to increase plt.title font size?

fontsize can be assigned inside dictionary fontdict which provides additional parameters fontweight, verticalalignment , horizontalalignment The below snippet should work plt.title(‘Temperature \n Humidity’, fontdict = {‘fontsize’ : 100})

Replace and overwrite instead of appending

You need seek to the beginning of the file before writing and then use file.truncate() if you want to do inplace replace: The other way is to read the file then open it again with open(myfile, ‘w’): Neither truncate nor open(…, ‘w’) will change the inode number of the file (I tested twice, once with Ubuntu 12.04 NFS and once with ext4). By the way, this … Read more

deleting rows in numpy array

I have an array that might look like this: Notice that one of the rows has a zero value at the end. I want to delete any row that contains a zero, while keeping any row that contains non-zero values in all cells. But the array will have different numbers of rows every time it … Read more

reducing number of plot ticks

Alternatively, if you want to simply set the number of ticks while allowing matplotlib to position them (currently only with MaxNLocator), there is pyplot.locator_params, You can specify specific axis in this method as mentioned below, default is both:

Detect whether a Python string is a number or a letter

Check if string is nonnegative digit (integer) and alphabet You may use str.isdigit() and str.isalpha() to check whether a given string is a nonnegative integer (0 or greater) and alphabetical character, respectively. Sample Results: Check for strings as positive/negative – integer/float str.isdigit() returns False if the string is a negative number or a float number. For example: If you want to also check for the negative integers and float, then you may … Read more