Python (practice)
22 flashcards · Programming Languages · by charlie42
Get list of unique values of a column in a df
df["Teacher ID"].unique()
Get first value of a column in a df
student_ID = df["Student ID"].iloc[0]
Drop several columns
df.drop(['B', 'C'], axis=1)
Rena me a column
df. rename(columns = {'old_col1':'new_col1', 'old_col2':'new_col2'})
Append an item to a list and return the new list
yourList = myList + [40]
List comprehension with condition
[x for x in list if x>2]
Check that a string contains a value
"value" in string
Drop first row in a df
full = full.iloc[1: , :]
Data format that a pd.DataFrame() method expects
How to go from this: to this:
zip(languages, versions)
What happens when you import a package?
Python runs all code in the __init__.py file
What happens when you import a file?
Python runs all code inside the file
Pandas: syntax for making a df from a dictionary
pd.DataFrame.from_dict
Pandas: what format from_dict expects?
Probable reason for this error: 'NoneType' object has no attribute 'X'
You probably forgot to return a value in a function
What can you do if you want to define several functions (e.g. add and subtract), and time the execution of each one?
Decorators def timer(f): def actual_function(f, args*): start = time() result = f(args*) end = time() print(end-start) return result @timer def add(a, b): return a+b @timer def subtract(a, b): return a-b add(1, 2)
What's a proper way to index, and to reassign a specific value in a dataframe? As opposed to a bad way to do it.
Chained indexing is bad, using .loc is good. Chaining example: df["Population"]["France"] .loc example: df.loc["France", "Population"]
What's the difference between creating a df through pd.Dataframe.from_dict() and pd.Dataframe(my_dict)
It's the same if the dictionary is column-oriented. To use an index-oriented dictionary use orient="Index" argument in from_dict()
What's None in python?
It's a value of type NoneType (similar to int, float, etc.) It's a singleton object: there can only be one of them defined in an interpreter section. Variables always have values in python, they're created when they're defined. So as a convention you can use the None object to signify an "empty" variable. For example function always return a value. If you didn't specify which, it will return the None object. It's created when python interpreter is initialized (in C), together with True, False,…
When you have a data file located in: your_repo/app/data/my_data.csv and you run python script like this: your_repo: python3 app/src/main.py what's the path to read the data?
"app/data/my_data.csv"
How to append a dataframe to an existing dataframe
train_set=pd.concat([train_set, train_ratings])
How to concatenate two lists
c = a + b