Python (Freecodecamp)
Pandas, Numpy, Jupyter
133 flashcards · Programming Languages · by charlie42
Convert to a decimal number
float(10)
Convert to integer
int(10.1)
int(9.9) vs round(9.9)
9 10
Convert to string
str(10)
Can list contain values of different data types?
Yes! ['Facebook', 0.0, 'USD', 2974676, 3.5]
Get size of a list
len(list)
Get last element of a list
list[-1]
What's list slicing
Select first 3 elements of a list
list[:3]
Select last 3 elements of a list
list[-3:]
list[2:4] selects which elements?
2, 3
open file
open(filepath)
how to import a method of a module
import method from module
sum of all elements in a list
sum(list)
syntax for else if
elif condition == True:
what does python try to do when creating a new key of dictionary?
convert it to an integer hash(key)
two things you can't do with dictionaries
use list or a dictionary as a key (can't be hashed into an integer) use both boolean value and integers 0 and 1 as keys, they will override each other since hash(True) == 1
content_ratings = {'4+': 4433, '9+': 987, '12+': 1155, '17+': 622} print(4433 in content_ratings)
False Because in used on a dictionary checks in keys
for loop
for item in list:
if value between two values
if 10000 < user_ratings <= 100000:
initialize a function
def do_a_thing(input): return output
import numpy
import numpy as np
create numpy array
my_array = np.array([1, 2, 3])
What does SIMD stand for?
Single Instruction Multiple Data
Concept of replacing for loops with operations applied to multiple data points at once
Vectorization
tuple vs list
you can't modify a tuple
get dimensions of a numpy array
my_array.shape
select single item from a list of list, and from 2d numpy array
list[1][2] array[1,2]
select first row of numpy array
array[0]
select specific columns of a numpy array
array[:, [1,5,10]]
select rows 100 to 200 of a numpy array
array[100:201]
np function vs method examples
function: np.median(array) method: array.max()
sum of each row of a 2d numpy array
array.sum(axis=1)
Jupyter notebook: create cell above
A
Jupyter notebook: create cell below
B
Jupyter notebook: delete cell
DD
Jupyter notebook: enter edit mode
Enter
Jupyter notebook: enter command mode
Esc
Jupyter notebook: switch to markdown
M
Jupyter notebook: switch to code mode
Y
Jupyter notebook: run and switch cell
shift+Enter
Jupyter notebook: run and keep current cell
command+Enter
Jupyter notebook: cut/pase
X/V
2 to the power of 3
2 ** 3
Numpy: fill row 2 of array with zeros
array[2] = 0 (will expand to the whole row)
a[::3]
every third element in the sequence seq[start:end:step]
Numpy: select first and last value of a = [1, 2, 3, 4] with binary indices
a[[True, False, False, True]]
Numpy: select all values of a=[1,2,3,4] that are NOT >2
a[ ~(a>2) ]
Numpy: syntax for and and or
&, |
Numpy: Create a numpy array of size 10, filled with zeros
np.zeros(10)
Numpy: Create a numpy array with values ranging from 10 to 49
np.arange(10, 50)
Numpy: Create a numpy matrix of 2*2 integers, filled with ones
np.ones([2,2], dtype=np.int)
Numpy: Create a numpy array with the odd numbers between 1 to 10
np.arange(1, 11, 2)
Numpy: Given the X numpy array, show the elements in reverse position
X[::-1]
Pandas: 3 differences between Pandas Series and a Python List
Series has a name Series has a type You can change indices of a series arbitrarily (can be strings)
Pandas: 1 difference and 1 similarity between Pandas Series and a Python Dictionary
Difference: Series is ordered Similarity: Series keys (indices) and values
Pandas: Two ways to index a Series (code)
my_series['my_index'] my_series.iloc[i]
Pandas: difference in accessing by indices between Pandas Series and Python List
Last index not included in python lists, but included in Series
Pandas: read csv
pd.read_csv(file_path)
Pandas: get statistics on dataset
ds.describe()
Pandas: What is a dataframe?
A collection of Series
Pandas: command to see how many non-null values there are in every column in the dataframe?
df.info()
Pandas: get types of each column in a dataframe?
df.dtypes()
Pandas: how to index a row of a dataframe (2 ways)? What type is returned?
df.loc['France'] df.iloc[2] Series
Pandas: how to index a column of a dataframe? What type is returned?
df['Population'] Series
Pandas: select the "Population" column for all rows from "France" to "Italy" from a dataframe
df.loc['France':'Italy', 'Population'] (upper limit is included)
Pandas: select the columns 1 to 5 for rows 2 and 10 from a dataframe
df.iloc[1:6, [2, 10]] (upper limit is not included)
Pandas: get columns "Population" and "GDP" for countries with population > 50'000 from a dataframe
df.loc[ df['Population'] > 50000 ], ['Population', 'GDP'] ]
Pandas: why do we use loc to filter dataframe by condition?
Because we filter rows by the index. The boolean array is indexed
Pandas: drop row with index "Canada" from a dataframe
df.drop('Canada')
Pandas: drop rows with indices "Canada" and "France" from a dataframe
df.drop(['Canada', 'France'])
Pandas: drop column "Population" from a dataframe
df.drop(columns=['Population'])
Pandas: example of broadcasting
Create a Series with indices matching the columns of the dataframe Subtract the Series from the dataset (The values from the Series will be substracted from the corresponding column of each row of the dataframe)
Pandas: does the drop operation modify the original dataframe?
No
Pandas: does this operation modify the original dataframe: df['Language'] = "English" ?
Yes
Pandas: how do we know if an operation will modify the original dataframe?
Usually the operations with an equals sign (=) in them will modify the dataframe, others won't
Get signature of a method
pd.read_csv?
Pandas: read csv without headers, add headers manually
df = read_csv('filepath.csv', header=None) df.columns = ['First column', 'Second column']
Pandas: two ways to create a Series
From a dictionary: s = pd.Series({ 'key1': 'value1', 'key2': 'value2' }, name = 'Column name') From an list: s = pd.Series( ['value1', 'value2'], index = ['key1', 'key2'], name = 'Column name' )
Pandas: filter Series by condition
s[s > 100]
Pandas: not, and, and not symbols when filtering Series
& | ~
Pandas: create a Series of a type float
pd.Series([1,2], dtype=float)
Pandas: sort a Series
X.sort_values()
Pandas: show just the "sex" column of the first 5 elements on marvel_df
marvel_df.iloc[:5]["sex"].to_frame() .loc will only work if marvel_df uses default pandas indexing (0, 1, 2, ...), which is not confirmed.
Pandas: modify the first_appearance of 'Vision' to year 1964
marvel_df.loc['Vision', "first_appearance"] = 1964
Pandas: plot the values of a column
df.column.plot()
Pandas: plot the histogram of a column
df.column.plot.hist()
Pandas: read a df from csv without headers, assign headers manually, set the index, and parse dates in one command
df = pd.read_csv( 'data/btc-market-price.csv', header=None, names=['Timestamp', 'Price'], index_col=0, parse_dates=True )
Pandas: 3 methods specific for column types. Example
str dt cat df['name'].str.split('-')
3 + np.nan
np.nan Any arithmetic operation involving np.nan returns np.nan, as NaN is treated as an undefined or missing value.
3 + None
TypeError None cannot be used in arithmetic operations with numbers in Python, so this expression raises a TypeError.
Filter nan values from a numpy array
a[~np.isnan(a)]
np.isfinite(np.nan)
False
pd.isnull(np.nan)
True
pd.isnull(None)
True
pd.isna(np.nan)
True
pd.isna(None)
True
Opposite of pd.isna and pd.isnull
pd.notna() pd.notnull()
np.array([1, np.nan, 2]).sum()
np.nan
pd.Series([1, np.nan, 2]).sum()
3