Categories
Python Answers

How to selectively escape percent (%) in Python strings?

Sometimes, we want to selectively escape percent (%) in Python strings.

In this article, we’ll look at how to selectively escape percent (%) in Python strings.

How to selectively escape percent (%) in Python strings?

To selectively escape percent (%) in Python strings, we put % before the % sign to escape it.

For instance, we write

elective_escape = "Print percent %% in sentence and not %s" % test

to escape the first % with %%.

Then we print the string, one % will be printed.

Conclusion

To selectively escape percent (%) in Python strings, we put % before the % sign to escape it.

Categories
Python Answers

How to animate a scatter plot with Python matplotlib?

Sometimes, we want to animate a scatter plot with Python matplotlib.

In this article, we’ll look at how to animate a scatter plot with Python matplotlib.

How to animate a scatter plot with Python matplotlib?

To animate a scatter plot with Python matplotlib, we can use the celluloid package.

To install it, we run

pip install celluloid

Then we use it by writing

import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from celluloid import Camera

numpoints = 10
points = np.random.random((2, numpoints))
colors = cm.rainbow(np.linspace(0, 1, numpoints))
camera = Camera(plt.figure())
for _ in range(100):
    points += 0.1 * (np.random.random((2, numpoints)) - .5)
    plt.scatter(*points, c=colors, s=100)
    camera.snap()
anim = camera.animate(blit=True)
anim.save('scatter.mp4')

to create random points with np.random.random.

Then we call cm.rainbow to assign color to the points.

Then we create the celluloid Camera object with the plt plots.

Next, we create a for loop and move the points in the loop with

points += 0.1 * (np.random.random((2, numpoints)) - .5)

Then we create a scatter plot of the points with

plt.scatter(*points, c=colors, s=100)

Next we call camera.snap() to snap a frame of the current plot.

Then we call `camera.animate to animate the frames.

And we call save to save the file as scatter.mp4.

Conclusion

To animate a scatter plot with Python matplotlib, we can use the celluloid package.

Categories
Python Answers

How to skip the headers when editing a csv file using Python?

Sometimes, we want to skip the headers when editing a csv file using Python.

In this article, we’ll look at how to skip the headers when editing a csv file using Python.

How to skip the headers when editing a csv file using Python?

To skip the headers when editing a csv file using Python, we can call next to skip the first row.

For instance, we write

with open("foo.csv", "rb") as infile, open("bar.csv", "wb") as outfile:
   reader = csv.reader(infile)
   next(reader, None)
   writer = csv.writer(outfile)
   for row in reader:
       writer.writerow(row)

to open the foo.csv and bar.csv files with open.

And then we call csv.reader to read infile into an iterator.

Then we call next with reader to skip the header row.

Then we call csv.writer with outfile to create the writer object.

Then we loop through the rows returned by reader and call writerow to write the row.

Conclusion

To skip the headers when editing a csv file using Python, we can call next to skip the first row.

Categories
Python Answers

How to create dataframe from a dictionary where entries have different lengths with Python Pandas?

Sometimes, we want to create dataframe from a dictionary where entries have different lengths with Python Pandas.

in this article, we’ll look at how to create dataframe from a dictionary where entries have different lengths with Python Pandas.

How to create dataframe from a dictionary where entries have different lengths with Python Pandas?

To create dataframe from a dictionary where entries have different lengths with Python Pandas, we can use the DataFrame class with the dict.

For instance, we write

import pandas as pd
import numpy as np

d = dict(A = np.array([1,2]), B = np.array([1,2,3,4]))
    
df = pd.DataFrame(dict([ (k, pd.Series(v)) for k,v in d.items() ]))

to create a dict with the 2 arrays with

d = dict(A = np.array([1,2]), B = np.array([1,2,3,4]))

Then we use the DataFrame class with the dict by creating another dict that we get from the dict d by calling pd.Series with d‘s values.

Then we use the new dict as the argument of DataFrame to create the data frame.

The missing values will be set to NaN.

Conclusion

To create dataframe from a dictionary where entries have different lengths with Python Pandas, we can use the DataFrame class with the dict.

Categories
Python Answers

How to open a file using the open with statement with Python?

Sometimes, we want to open a file using the open with statement with Python.

In this article, we’ll look at how to open a file using the open with statement with Python.

How to open a file using the open with statement with Python?

To open a file using the open with statement with Python, we cann open after with.

For instance, we write

with open(newfile, 'w') as outfile:
    with open(oldfile, 'r', encoding='utf-8') as infile:
        # ...

to call open after with to open newfile with write permission and assign the return file handle to outfile.

Likewise, we call open after with to open oldfile with read permission and assign the return file handle to infile and set the encoding of the file to Unicode by setting encoding to 'utf-8'.

Conclusion

To open a file using the open with statement with Python, we cann open after with.