Categories
Python Answers

How to support equivalence (“equality”) check in Python classes?

Sometimes, we want to support equivalence ("equality") check in Python classes.

In this article, we’ll look at how to support equivalence ("equality") check in Python classes.

How to support equivalence ("equality") check in Python classes?

To support equivalence ("equality") check in Python classes, we can override the __eq__ method in the Python class.

For instance, we write:

class Number:
    def __init__(self, number):
        self.number = number

    def __eq__(self, other):
        if isinstance(other, Number):
            return self.number == other.number
        return False

n1 = Number(1)
n2 = Number(1)
print(n1 == n2)

to add the __eq__ method which checks for the value of self.number to determine equality of a Number instances instead of using the default way, which is to compare object ID for equality.

We only do the check if other is a Number instance. Otherwise, we return False directly.

Next, we create 2 Number instances with the same value for self.number.

Therefore, n1 and n2 should be equal according to our check, and so True is printed.

Conclusion

To support equivalence ("equality") check in Python classes, we can override the __eq__ method in the Python class.

Categories
Python Answers

How to write a Python list of lists to a CSV file?

Sometimes, we want to write a Python list of lists to a CSV file.

In this article, we’ll look at how to write a Python list of lists to a CSV file.

How to write a Python list of lists to a CSV file?

To write a Python list of lists to a CSV file, we can use the csv module.

For instance, we write:

import csv

a = [[1.2, 'abc', 3], [1.2, 'werew', 4], [1.4, 'qew', 2]]

with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(a)

to pass the nested list a as the argument of writer.writerows to write the file to the out.csv file.

We open the out.csv file with 'w' permission to let us write to the file.

And we set the new line character to an empty string as specified with newline="".

Then we call csv.writer with f to create the writer object and call writerows to write to the file.

Therefore, out.csv has:

1.2,abc,3
1.2,werew,4
1.4,qew,2

Conclusion

To write a Python list of lists to a CSV file, we can use the csv module.

Categories
Python Answers

How to write Unicode text to a text file with Python?

Sometimes, we want to write Unicode text to a text file with Python.

In this article, we’ll look at how to write Unicode text to a text file with Python.

How to write Unicode text to a text file with Python?

To write Unicode text to a text file with Python, we can call the file handle’s write method with a Unicode encoded string.

For instance, we write:

foo = u'Δ, Й, ק, ‎ م, ๗, あ, 叶, 葉, and 말.'
f = open('test', 'w')
f.write(foo)
f.close()

f = open('test', 'r')
print(f.read())

We define the string foo with a Unicode string.

Then we open the test file with open with write permission.

Next, we call f.write with foo and then close the file with close.

Then to read the file, we call open again with the file path and 'r' to get read permission.

And then we call f.read.

Therefore print should print 'Δ, Й, ק, ‎ م, ๗, あ, 叶, 葉, and 말.'.

Conclusion

To write Unicode text to a text file with Python, we can call the file handle’s write method with a Unicode encoded string.

Categories
Python Answers

How to detect and exclude outliers in Pandas data frame with Python?

Sometimes, we want to detect and exclude outliers in Pandas data frame with Python.

In this article, we’ll look at how to detect and exclude outliers in Pandas data frame with Python.

How to detect and exclude outliers in Pandas data frame with Python?

To detect and exclude outliers in Pandas data frame with Python, we can use NumPy to return a new DataFrame that has values within 3 standard deviations from the mean.

To do this, we can write:

import pandas as pd
import numpy as np

df = pd.DataFrame({'Data':np.random.normal(size=200)})
new_df = df[np.abs(df.Data-df.Data.mean()) <= (3*df.Data.std())]
print(new_df)

We create a Pandas DataFrame with a normal distribution with sample size 200 with np.random.normal.

Then we pick the values that are within 3 standard deviations from the mean with df[np.abs(df.Data-df.Data.mean()) <= (3*df.Data.std())].

And we assign the returned DataFrame to new_df.

Therefore, new_df is something like:

         Data
0    0.300805
1   -0.474140
2   -0.326278
3    0.566571
4   -1.391077
..        ...
195  0.500637
196  0.341858
197 -1.058419
198 -0.565920
199 -1.008344

[200 rows x 1 columns]

according to print.

Conclusion

To detect and exclude outliers in Pandas data frame with Python, we can use NumPy to return a new DataFrame that has values within 3 standard deviations from the mean.

Categories
Python Answers

How to list a directory tree in Python?

Sometimes, we want to list a directory tree in Python.

In this article, we’ll look at how to list a directory tree in Python.

How to list a directory tree in Python?

To list a directory tree in Python, we can use the os.walk method.

For instance, we write:

import os

for dirname, dirnames, filenames in os.walk('.'):
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))

    for filename in filenames:
        print(os.path.join(dirname, filename))

We call os.walk with the root path string to return an iterator with tuples with dirname, dirnames, and filenames.

Then we can loop through dirnames and filenames and get the subdirectories and files in each directory respectively.

We call os.path.join to get the full subdirectory and file paths respectively.

Therefore, we get something like:

./.upm
./pyproject.toml
./poetry.lock
./test.csv
./art.png
./.breakpoints
./main.py
./.upm/store.json

from the print calls.

Conclusion

To list a directory tree in Python, we can use the os.walk method.