Categories
Python Answers

How to read specific lines from a file by line number with Python?

Sometimes, we want to read specific lines from a file by line number with Python.

In this article, we’ll look at how to read specific lines from a file by line number with Python.

How to read specific lines from a file by line number with Python?

To read specific lines from a file by line number with Python, we can use the open and enumerate functions.

For instance, if we have the following text file:

foo.txt:

foo
bar
baz

Then we can read the 3rd line of the file by writing:

with open("foo.txt") as fp:
    for i, line in enumerate(fp):
        if i == 2:
            print(line)

We call open with the path to the text file.

Then we loop through each line with the index i and line returned by enumerate.

We check if i is 2 to check if it’s reading the 3rd line.

If that’s True, then we call print to print the line.

So we see ‘baz’ printed.

Conclusion

To read specific lines from a file by line number with Python, we can use the open and enumerate functions.

Categories
Python Answers

How to convert a Python dict into a Pandas DataFrame?

Sometimes, we want to convert a Python dict into a Pandas DataFrame.

In this article, we’ll look at how to convert a Python dict into a Pandas DataFrame.

How to convert a Python dict into a Pandas DataFrame?

To convert a Python dict into a Pandas DataFrame, we can use the DataFrame constructor with an iterator with the tuples of the key-value pairs.

For instance, we write:

import pandas as pd

d = {
    u'2012-06-08': 388,
    u'2012-06-09': 388,
    u'2012-06-10': 388,
    u'2012-06-11': 389,
    u'2012-06-12': 389,
    u'2012-06-13': 389
}
df = pd.DataFrame(d.items())
print(df)

to convert the d dictionary to a DataFrame.

We call d.items to return the iterator with the tuples of the key-value pairs and use that as the argument of DataFrame.

And then we assign the returned DataFrame to df.

Therefore, we get:

            0    1
0  2012-06-08  388
1  2012-06-09  388
2  2012-06-10  388
3  2012-06-11  389
4  2012-06-12  389
5  2012-06-13  389

as the value of df.

Conclusion

To convert a Python dict into a Pandas DataFrame, we can use the DataFrame constructor with an iterator with the tuples of the key-value pairs.

Categories
Python Answers

How to add a progress bar with Python?

Sometimes, we want to add a progress bar with Python.

In this article, we’ll look at how to add a progress bar with Python.

How to add a progress bar with Python?

To add a progress bar with Python, we can use the tqdm package.

To install it, we run:

pip install tqdm

Then we can use it by writing:

from time import sleep
from tqdm import tqdm
for i in tqdm(range(10)):
    sleep(3)

We call tqdm with the range(10) iterator to print out the progress 10 times.

Therefore, we should see the latest progress printed every 3 seconds.

Conclusion

To add a progress bar with Python, we can use the tqdm package.

Categories
Python Answers

How to set environment variables in Python?

Sometimes, we want to set environment variables in Python.

In this article, we’ll look at how to set environment variables in Python.

How to set environment variables in Python?

To set environment variables in Python, we can put an entry the os.environ dictionary.

For instance, we write:

import os

os.environ["DEBUG"] = "1"
print(os.environ["DEBUG"])

to set the DEBUG environment variable to '1'.

And to get the value of the DEBUG environment variable, we write:

print(os.environ["DEBUG"])

and we should see '1' printed.

Conclusion

To set environment variables in Python, we can put an entry the os.environ dictionary.

Categories
Python Answers

How to take subarrays from Python numpy array with given stride/step size?

Sometimes, we want to take subarrays from Python numpy array with given stride/step size.

In this article, we’ll look at how to take subarrays from Python numpy array with given stride/step size.

How to take subarrays from Python numpy array with given stride/step size?

To take subarrays from Python numpy array with given stride/step size, we can use the lib.atride_ticks.as_strided method.

For instance, we write:

import numpy as np


def strided_app(a, L, S):
    nrows = ((a.size - L) // S) + 1
    n = a.strides[0]
    return np.lib.stride_tricks.as_strided(a,
                                           shape=(nrows, L),
                                           strides=(S * n, n))


a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
s = strided_app(a, L=5, S=3)
print(s)

We create the strided_app function that takes the array a.

L is the length of the chunk.

And S is the stride or step size.

We compute the number of rows with ((a.size - L) // S) + 1.

Then we get the first chunk with a.strides[0].

And then we call np.lib.stride_tricks.as_strided to compute the chunks with the shape of the nested array and the strides set to the start and end index of the range of items from the original array used to form the chunks in the new array.

Therefore, s is:

[[ 1  2  3  4  5]
 [ 4  5  6  7  8]
 [ 7  8  9 10 11]]

Conclusion

To take subarrays from Python numpy array with given stride/step size, we can use the lib.atride_ticks.as_strided method.