Intermediate Python for Data Science Flashcards
Give an example for plotting
The most basic plot is the line plot. A general recipe is given here.
import matplotlib.pyplot as plt
plt.plot(x,y)
plt.show()
How do you ‘log’ the scale of an axis for plotting?
plt.xscale(‘log’)
Exapmle of how to change Yticks
Filip has demonstrated how you could control the y-ticks by specifying two arguments:
plt.yticks([0,1,2], [“one”,”two”,”three”])
In this example, the ticks corresponding to the numbers 0, 1 and 2 will be replaced by one, two and three, respectively.
Dictionaries can contain dictionaries.
Remember lists? They could contain anything, even other lists. Well, for dictionaries the same holds. Dictionaries can contain key:value pairs where the values are again dictionaries.
Good to Remember
In the sample code on the right, the same cars data is imported from a CSV files as a Pandas DataFrame. To select only the cars_per_cap column from cars, you can use:
cars[‘cars_per_cap’]
cars[[‘cars_per_cap’]]
The single bracket version gives a Pandas Series, the double bracket version gives a Pandas DataFrame.
To Remember
Square brackets can do more than just selecting columns. You can also use them to get rows, or observations, from a DataFrame. The following call selects the first five rows from the cars DataFrame:
cars[0:5]
To Remember
Each pair of commands here gives the same result.
cars. loc[‘RU’]
cars. iloc[4]
cars. loc[[‘RU’]]
cars. iloc[[4]]
cars. loc[[‘RU’, ‘AUS’]]
cars. iloc[[4, 1]]
Using the ‘for’ loop
fam = [1.73, 1.68, 1.71, 1.89]
for height in fam :
print(height)
example of how to use the ennumerate ()
fam = [1.73, 1.68, 1.71, 1.89]
for index, height in enumerate(fam) :
print(“index “ + str(index) + “: “ + str(height))
How to iterate over a dictionary?
world = { “afghanistan”:30.55, “albania”:2.77, “algeria”:39.21 }
for key, value in world.items() :
print(key + “ – “ + str(value))
How do you iterate over a 2D array?
for x in np.nditer(my_array) : …
matplotlib : To Remember
Remember how you could use matplotlib to build a line plot?
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.show()
The first list you pass is mapped onto the x axis and the second list is mapped onto the y axis.
If you pass only one argument, Python will know what to do and will use the index of the list to map onto the x axis, and the values in the list onto the y axis.