Categories
Python Answers

How to get intersecting rows across two 2D Python NumPy arrays?

Sometimes, we want to get intersecting rows across two 2D Python NumPy arrays.

In this article, we’ll look at how to get intersecting rows across two 2D Python NumPy arrays.

How to get intersecting rows across two 2D Python NumPy arrays?

To get intersecting rows across two 2D Python NumPy arrays, we can convert the arrays to sets and then use the & operator to get the intersection of both sets.

For instance, we write:

import numpy as np

A = np.array([[1, 4], [2, 5], [3, 6]])
B = np.array([[1, 4], [3, 6], [7, 8]])
aset = set([tuple(x) for x in A])
bset = set([tuple(x) for x in B])
intersection = np.array([x for x in aset & bset])
print(intersection)

We have 2 arrays of lists A and B that we created with np.array.

Then we convert both arrays to sets with set.

And we convert each entry in A and B to tuples with tuple.

Next, we get the common entries from each set with [x for x in aset & bset] and put them in a list.

Finally, we convert the list back to an array with np.array.

Therefore, intersection is:

[[1 4]
 [3 6]]

Conclusion

To get intersecting rows across two 2D Python NumPy arrays, we can convert the arrays to sets and then use the & operator to get the intersection of both sets.

Categories
Python Answers

How to initialize a dictionary of empty lists in Python?

Sometimes, we want to initialize a dictionary of empty lists in Python.

In this article, we’ll look at how to initialize a dictionary of empty lists in Python.

How to initialize a dictionary of empty lists in Python?

To initialize a dictionary of empty lists in Python, we can use dictionary comprehension.

For instance, we write:

data = {k: [] for k in range(2)}
print(data)

to create a dictionary with 2 entries that are both set to empty lists as values.

Therefore, data is {0: [], 1: []}.

Conclusion

To initialize a dictionary of empty lists in Python, we can use dictionary comprehension.

Categories
Python Answers

How to start a function at a given time with Python?

Sometimes, we want to start a function at a given time with Python.

In this article, we’ll look at how to start a function at a given time with Python.

How to start a function at a given time with Python?

To start a function at a given time with Python, we can use the timedelta function to set the delay before running the function.

For instance, we write:

from datetime import datetime, timedelta
import threading


def update():
    print('hello world')


now = datetime.now()
run_at = now + timedelta(seconds=3)
delay = (run_at - now).total_seconds()
threading.Timer(delay, update).start()

to create the update function that we want to run after a 3 second delay.

To do this, we get the current date time with datetime.now.

And then we add the 3 seconds time difference by calling the timedelta function and add the returned time delta object to now.

Next, we calculate the delay with (run_at - now).total_seconds().

Finally, we call the Timer constructor with the delay and the update function to create the thread.

And we call start on the Timer instance to run the function after the specified delay.

Therefore, we should see 'hello world' printed after a 3 seconds delay.

Conclusion

To start a function at a given time with Python, we can use the timedelta function to set the delay before running the function.

Categories
Python Answers

How to split a column of tuples in a Python Pandas data frame?

Sometimes, we want to split a column of tuples in a Python Pandas data frame.

In this article, we’ll look at how to split a column of tuples in a Python Pandas data frame.

How to split a column of tuples in a Python Pandas data frame?

To split a column of tuples in a Python Pandas data frame, we can use the column’s tolist method.

For instance, we write:

import pandas as pd

df = pd.DataFrame({'a': [1, 2], 'b': [(1, 2), (3, 4)]})
df2 = pd.DataFrame(df['b'].tolist(), index=df.index)
print(df2)

We create the df data frame with the pd.DataFrame class and a dictionary.

Then we create a new data frame from df by using df['b'].tolist() to get column b and convert it to a list.

And we set the index to df.index.

This will split the tuple elements into separate entries in each row.

Therefore, df2 is:

   0  1
0  1  2
1  3  4

Conclusion

To split a column of tuples in a Python Pandas data frame, we can use the column’s tolist method.

Categories
Python Answers

How to convert a list of lists into a Python NumPy array?

Sometimes, we want to convert a list of lists into a Python NumPy array.

In this article, we’ll look at how to convert a list of lists into a Python NumPy array.

How to convert a list of lists into a Python NumPy array?

To convert a list of lists into a Python NumPy array, we can create an array of arrays with the numpy.array method.

For instance, we write:

import numpy

x = [[1, 2], [1, 2, 3], [1]]
y = numpy.array([numpy.array(xi) for xi in x], dtype=object)
print(y)

We call numpy.array with a list that converts the lists inside x to array with numpy.array(xi) for xi in x.

And we set dtype to object.

As a result, we see that y is [array([1, 2]) array([1, 2, 3]) array([1])].

Conclusion

To convert a list of lists into a Python NumPy array, we can create an array of arrays with the numpy.array method.