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.

Categories
Python Answers

How to parse a JSON response from the Python requests library?

Sometimes, we want to parse a JSON response from the Python requests library.

In this article, we’ll look at how to parse a JSON response from the Python requests library.

How to parse a JSON response from the Python requests library?

To parse a JSON response from the Python requests library, we can use the response.json method.

For instance, we write:

import requests

response = requests.get('https://yesno.wtf/api')
json_data = response.json()
print(json_data)

We call requests.get with a URL.

Then we call response.json to return the JSON response as a dictionary.

And then we assign that to json_data.

Therefore, json_data is:

{'answer': 'yes', 'forced': False, 'image': 'https://yesno.wtf/assets/yes/8-2f93962e2ab24427df8589131da01a4d.gif'}

Conclusion

To parse a JSON response from the Python requests library, we can use the response.json method.

Categories
Python Answers

How to dump a NumPy array into a CSV file with Python?

Sometimes, we want to dump a NumPy array into a CSV file with Python

In this article, we’ll look at how to dump a NumPy array into a CSV file with Python

How to dump a NumPy array into a CSV file with Python?

To dump a NumPy array into a CSV file with Python, we can use the savetxt method.

For instance, we write:

import numpy
a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
numpy.savetxt("foo.csv", a, delimiter=",")

We call numpy.asarray with a nested list to create the a NumPy array.

Then we call savetxt with the path to the file we want to save to, the a array, and the delimiter for the cells.

As a result, in foo.txt, we get:

1.000000000000000000e+00,2.000000000000000000e+00,3.000000000000000000e+00
4.000000000000000000e+00,5.000000000000000000e+00,6.000000000000000000e+00
7.000000000000000000e+00,8.000000000000000000e+00,9.000000000000000000e+00

Conclusion

To dump a NumPy array into a CSV file with Python, we can use the savetxt method.