Categories
Python Answers

How to extract the n-th elements from a list of tuples with Python?

Sometimes, we want to extract the n-th elements from a list of tuples with Python.

In this article, we’ll look at how to extract the n-th elements from a list of tuples with Python.

How to extract the n-th elements from a list of tuples with Python?

To extract the n-th elements from a list of tuples with Python, we can use list comprehension.

For instance, we write:

elements = [(1, 1, 1), (2, 3, 7), (3, 5, 10)]
n = 1
e = [x[n] for x in elements]
print(e)

We get the n-th element from each tuple and put them into a list with [x[n] for x in elements].

x is the tuple being retrieved.

Therefore, e is [1, 3, 5].

Conclusion

To extract the n-th elements from a list of tuples with Python, we can use list comprehension.

Categories
Python Answers

How to test whether a Python NumPy array contains a given row?

Sometimes, we want to test whether a Python NumPy array contains a given row.

In this article, we’ll look at how to test whether a Python NumPy array contains a given row.

How to test whether a Python NumPy array contains a given row?

To test whether a Python NumPy array contains a given row, we can convert the NumPy array to a list and then use the in operator to check whether the list is in the nested list.

For instance, we write:

import numpy as np

a = np.array([[1, 2], [10, 20], [100, 200]])
l = a.tolist()
print([1, 2] in l)
print([1, 200] in l)

We can np.array with a nested list to create an array.

Then we call a.tolist to convert the NumPy array back to a list.

Next, we use the in operator to check whether [1, 2] and [1, 200] is in l.

Therefore, print should print:

True
False

since [1, 2] is in l and [1, 200] isn’t.

Conclusion

To test whether a Python NumPy array contains a given row, we can convert the NumPy array to a list and then use the in operator to check whether the list is in the nested list.

Categories
Python Answers

How to extract part of a regex match with Python?

Sometimes, we want to extract part of a regex match with Python.

In this article, we’ll look at how to extract part of a regex match with Python.

How to extract part of a regex match with Python?

To extract part of a regex match with Python, we can use the re.search method with a regex that gets a match from within a pattern.

For instance, we write:

import re

html = '<title>hell world</title>'
title_search = re.search('<title>(.*)</title>', html, re.IGNORECASE)

if title_search:
    title = title_search.group(1)
print(title)

We want to extract the text between the title tags in html.

To do that, we call re.search with '<title>(.*)</title> to get the content between the title tags.

Then we pass in html and re.IGNORECASE as the other arguments to search html in a case-insensitive manner.

Then we get the match from the regex group with title_search.group(1).

Therefore, title should be 'hello world'.

Conclusion

To extract part of a regex match with Python, we can use the re.search method with a regex that gets a match from within a pattern.

Categories
Python Answers

How to merge multiple data frames with Python Pandas?

Sometimes, we want to merge multiple data frames with Python Pandas.

In this article, we’ll look at how to merge multiple data frames with Python Pandas.

How to merge multiple data frames with Python Pandas?

To merge multiple data frames with Python Pandas, we can use the concat method.

For instance, we write:

import pandas as pd

data1 = {'a': [1, 2, 3]}
data2 = {'a': [4, 5, 6]}
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)

merged_df = pd.concat([df1, df2])
print(merged_df)

We create 2 data frames with pd.DataFrame and 2 dictionaries.

Then we call pd.concat with the data frames in the list and assign the returned data frame to merged_df.

Therefore, merged_df is:

   a
0  1
1  2
2  3
0  4
1  5
2  6

Conclusion

To merge multiple data frames with Python Pandas, we can use the concat method.

Categories
Python Answers

How to find all the factors of a number in Python?

Sometimes, we want to find all the factors of a number in Python.

In this article, we’ll look at how to find all the factors of a number in Python.

How to find all the factors of a number in Python?

To find all the factors of a number in Python, we can use the functools module.

For instance, we write:

from functools import reduce


def factors(n):
    return set(
        reduce(list.__add__, ([i, n // i]
                              for i in range(1,
                                             int(n**0.5) + 1) if n % i == 0)))


print(factors(50))

We define the factors function which takes the number n to get the factors from.

In the function, we call reduce with list.__add__ as the function to call to to add the factors into a list.

Then we compute the factors with ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0) to compute the factors by getting all the numbers i that can divide n evenly.

Finally, we call set to remove the duplicates from the list returned by reduce.

Therefore, we should see {1, 2, 5, 10, 50, 25} from the print output.

Conclusion

To find all the factors of a number in Python, we can use the functools module.