Categories
Python Answers

How to extract first item of each sublist with Python?

Sometimes, we want to extract first item of each sublist with Python.

In this article, we’ll look at how to extract first item of each sublist with Python.

How to extract first item of each sublist with Python?

To extract first item of each sublist with Python, we can use list comprehension.

For instance, we write:

lst = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
lst2 = [item[0] for item in lst]
print(lst2)

to get the first item from each list in lst by getting item[0] from each item, which is each list in lst.

Therefore, lst2 is ['a', 1, 'x'].

Conclusion

To extract first item of each sublist with Python, we can use list comprehension.

Categories
Python Answers

How to download a picture via urllib and Python?

Sometimes, we want to download a picture via urllib and Python.

In this article, we’ll look at how to download a picture via urllib and Python.

How to download a picture via urllib and Python?

To download a picture via urllib and Python, we can use the urllib.request.urlretrieve method.

For instance, we write:

import urllib.request

urllib.request.urlretrieve(
    "https://i.picsum.photos/id/1055/200/300.jpg?hmac=RkWuwIAp7D4g_2_g01yQSz2pdKBzYeFDEjq86_12OHg",
    "pic.jpg")

to call urllib.request.urlretrieve with the picture URL and the file path to save the picture to.

A GET request will then be made to download the image.

Conclusion

To download a picture via urllib and Python, we can use the urllib.request.urlretrieve method.

Categories
Python Answers

How to create Pandas DataFrame from a string with Python?

Sometimes, we want to create Pandas DataFrame from a string with Python.

In this article, we’ll look at how to create Pandas DataFrame from a string with Python.

How to create Pandas DataFrame from a string with Python?

To create Pandas DataFrame from a string with Python, we can use the StringIO module.

For instance, we write:

from io import StringIO
import pandas as pd

TESTDATA = StringIO("""col1;col2;col3
    1;4.4;99
    2;4.5;200
    3;4.7;65
    4;3.2;140
    """)

df = pd.read_csv(TESTDATA, sep=";")
print(df)

We have the TESTDATA string with some CSV test data.

Then we call read_csv with TESTDATA to read the string into a DataFrame.

We set the sep parameter to set the separator used by the CSV string so the data will parse correctly.

Therefore, df is:

   col1  col2  col3
0     1   4.4    99
1     2   4.5   200
2     3   4.7    65
3     4   3.2   140

Conclusion

To create Pandas DataFrame from a string with Python, we can use the StringIO module.

Categories
Python Answers

How to repeat a function every ‘n’ seconds with Python threading.timer?

Sometimes, we want to repeat a function every ‘n’ seconds with Python threading.timer.

In this article, we’ll look at how to repeat a function every ‘n’ seconds with Python threading.timer.

How to repeat a function every ‘n’ seconds with Python threading.timer?

To repeat a function every ‘n’ seconds with Python threading.timer, we can create a subclass of Thread and call the start method on the subclass instance.

For instance, we write:

from threading import Timer, Thread, Event


class MyThread(Thread):
    def __init__(self, event):
        Thread.__init__(self)
        self.stopped = event

    def run(self):
        while not self.stopped.wait(0.5):
            print("my thread")


stopFlag = Event()
thread = MyThread(stopFlag)
thread.start()

We creatr the MyThread class which inherits from Thread.

In the class, we have the stopped property which is set to event.

And we have the run method with code that runs repeatedly.

We keep running the while loop until the stopFlag.set() is called.

Then we create an instance of MyThread with stopFlag as the argument.

And we call start on the thread.

Now we should see "my thread" repeatedly.

Conclusion

To repeat a function every ‘n’ seconds with Python threading.timer, we can create a subclass of Thread and call the start method on the subclass instance.

Categories
Python Answers

How to run functions in parallel with Python?

Sometimes, we want to run functions in parallel with Python.

In this article, we’ll look at how to run functions in parallel with Python.

How to run functions in parallel with Python?

To run functions in parallel with Python, we can use the multiprocessing module.

For instance, we write:

from multiprocessing import Process


def func1():
    print('func1: starting')
    for i in range(10000000):
        pass
    print('func1: finishing')


def func2():
    print('func2: starting')
    for i in range(10000000):
        pass
    print('func2: finishing')


if __name__ == '__main__':
    p1 = Process(target=func1)
    p1.start()
    p2 = Process(target=func2)
    p2.start()
    p1.join()
    p2.join()

We have func1 and func2 functions that we want to run.

Then we use the Process class to create the processes from the functions.

Then we call start to start the processes.

And we call join to join each process.

Therefore, we see:

func1: starting
func2: starting
func1: finishing
func2: finishing

printed.

Conclusion

To run functions in parallel with Python, we can use the multiprocessing module.