Intermediate Level

How to create a NumPy array of evenly spaced values between a given range?


arr = np.arange(10,100,5)
arr

How to create a DataFrame from a list of lists or list of tuples?


data = [
[1,'Alice',88],
[2, 'Bob',90],
[3, 'Charlie',92]
]
df = pd.DataFrame(data, columns=["id","name","marks"])
data = [
(1,"Alice"),
(2,"Bob"),
(3,"Charlie"),
]
df = pd.DataFrame(data, columns=["id", "name"])

How to handle missing data in a pandas DataFrame?


data = [
[np.nan, 10,20],
[101, 102,103],
[100, 200,np.nan]
]
df = pd.DataFrame(data, columns=["id","qty","price"])
df
id qty price
0 NaN 10 20.0
1 101.0 102 103.0
2 100.0 200 NaN
new_df = df.dropna()

new_df
id qty price
1 101.0 102 103.0
new_df = df.ffill()

new_df
id qty price
0 NaN 10 20.0
1 101.0 102 103.0
2 100.0 200 103.0
new_df = df.bfill()

new_df
id qty price
0 101.0 10 20.0
1 101.0 102 103.0
2 100.0 200 NaN

How to select rows and columns from a DataFrame using loc and iloc?


data = [
[1,'Alice',88],
[2, 'Bob',90],
[3, 'Charlie',92]
]
df = pd.DataFrame(data, columns=["id","name","marks"])

df
id name marks
0 1 Alice 88
1 2 Bob 90
2 3 Charlie 92
df.iloc[0:2,:]

id name marks
0 1 Alice 88
1 2 Bob 90
df.loc[0:2,['id', 'marks']]
id marks
0 1 88
1 2 90
2 3 92

How to perform element-wise operations on a NumPy array?


arr = np.array([1,2,3,4,5])

arr*2
lst = [1,2,3,4,5]

lst*2