Categories
Python Answers

How to programmatically set an attribute with Python?

Sometimes, we want to programmatically set an attribute with Python.

In this article, we’ll look at how to programmatically set an attribute with Python.

How to programmatically set an attribute with Python?

To programmatically set an attribute with Python, we can use the setattr function.

For instance, we write:

class C:
    foo = 1


c = C()
setattr(c, 'bar', 2)

print(c.bar)

We have the C class with the foo attribute.

Then we create an instance of C and assign it to c.

Next, we add the bar attribute to c with setattr(c, 'bar', 2).

Therefore, c.bar is now 2.

Conclusion

To programmatically set an attribute with Python, we can use the setattr function.

Categories
Python Answers

How to search for a string in text files with Python?

Sometimes, we want to search for a string in text files with Python.

In this article, we’ll look at how to search for a string in text files with Python.

How to search for a string in text files with Python?

To search for a string in text files with Python, we can use the in operator.

For instance, if we have the following text file:

example.txt

blablabla

Then we write:

with open('example.txt') as f:
    if 'blabla' in f.read():
        print("true")

We call open with the path of the text file to open.

Then we call f.read to read the file’s contents into a string.

And then we use the in operator to check if the text we’re looking for is in the string returned by read.

Since this is True, we see 'true' printed.

Conclusion

To search for a string in text files with Python, we can use the in operator.

Categories
Python Answers

How to split a string by a delimiter in Python?

Sometimes, we want to split a string by a delimiter in Python.

In this article, we’ll look at how to split a string by a delimiter in Python.

How to split a string by a delimiter in Python?

To split a string by a delimiter in Python, we can use the string’s split method.

For instance, we write:

a = "MATCHES__STRING".split("__")
print(a)

We call split on the string with the separator we want to split the string with as the argument.

Then we assign the returned list to a.

Therefore, a is ['MATCHES', 'STRING'].

Conclusion

To split a string by a delimiter in Python, we can use the string’s split method.

Categories
Python Answers

How to get indices of N maximum values in a Python NumPy array?

Sometimes, we want to get indices of N maximum values in a Python NumPy array.

In this article, we’ll look at how to get indices of N maximum values in a Python NumPy array.

How to get indices of N maximum values in a Python NumPy array?

To get indices of N maximum values in a Python NumPy array, we can use the argpartition method.

For instance, we write:

import numpy as np

a = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
ind = np.argpartition(a, -4)[-4:]
print(ind)

We call np.array with a list to create a Numpy array.

Then we call np.argpartition with a and -4 and [-4:] to get the top 4 elements in the array.

Therefore, ind is [1 5 8 0].

Conclusion

To get indices of N maximum values in a Python NumPy array, we can use the argpartition method.

Categories
Python Answers

How to apply a function to two columns of Pandas DataFrame in Python?

Sometimes, we want to apply a function to two columns of Pandas DataFrame in Python.

In this article, we’ll look at how to apply a function to two columns of Pandas DataFrame in Python.

How to apply a function to two columns of Pandas DataFrame in Python?

To apply a function to two columns of Pandas DataFrame in Python, we can use the DataFrame’s apply method.

For instance, we write:

import pandas as pd

df = pd.DataFrame({
    'ID': ['1', '2', '3'],
    'col_1': [0, 2, 3],
    'col_2': [1, 4, 5]
})
mylist = ['a', 'b', 'c', 'd', 'e', 'f']


def get_sublist(sta, end):
    return mylist[sta:end + 1]


df['col_3'] = df.apply(lambda x: get_sublist(x.col_1, x.col_2), axis=1)
print(df)

We frame the df DataFrame with some data in it.

And we have the mylist list that we want to add to DataFrame as another column.

Next, we create the get_sublist function that returns a slice of mylist.

Then we call df.apply with a function that calls get_sublist with the start and end indexes and set that as the value of the col_3 column of the DataFrame.

Therefore, df is:

  ID  col_1  col_2      col_3
0  1      0      1     [a, b]
1  2      2      4  [c, d, e]
2  3      3      5  [d, e, f]

Conclusion

To apply a function to two columns of Pandas DataFrame in Python, we can use the DataFrame’s apply method.