Python: Built-in Functions vs. For & If Loops – 5 Programs Explained

Whether you're a beginner or brushing up on your skills, these are the real-world questions Python learners ask most about key libraries in data science. Let’s dive in! 🐍
df.fillna(0) # Replace NaNs with 0
df.dropna() # Remove rows with NaNs
df.isna().sum() # Count missing values per column
pd.merge(df1, df2, on='id', how='inner') # inner, left, right, outer
loc[]
and iloc[]
?loc[]
uses labels (e.g., column names)
iloc[]
uses integer positions
df.loc[0, 'name'] # label-based
df.iloc[0, 1] # index-based
df.groupby('category')['sales'].sum()
df['date'] = pd.to_datetime(df['date'])
NumPy arrays are faster and support vectorized operations.
Use less memory and are more efficient for math-heavy tasks.
Broadcasting allows operations between arrays of different shapes.
arr = np.array([1, 2, 3])
arr + 5 # [6, 7, 8] — scalar is broadcasted
np.zeros((3,3)) # 3x3 of zeros
np.ones((2,2)) # 2x2 of ones
np.random.rand(4) # 1D array of 4 random floats
arr = np.array([1, 2, 3])
np.sqrt(arr)
np.log(arr)
arr * 2
arr.reshape(3, 2) # reshape to 3x2
arr.flatten() # convert to 1D
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("Line Chart")
plt.show()
plt.plot(x, y, color='green', linestyle='--', linewidth=2)
plt.figure(figsize=(10,5))
plt.plot()
and plt.scatter()
?plot()
is for line charts
scatter()
is for point plots
plt.scatter(x, y)
plt.savefig("my_plot.png")
plt.subplot(1, 2, 1) # 1 row, 2 cols, first plot
plt.plot(x1, y1)
plt.subplot(1, 2, 2) # second plot
plt.plot(x2, y2)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
LinearRegression()
LogisticRegression()
RandomForestClassifier()
KNeighborsClassifier()
SVC()
(Support Vector Classifier)
from sklearn.metrics import accuracy_score, confusion_matrix
accuracy_score(y_test, y_pred)
confusion_matrix(y_test, y_pred)
fit()
, transform()
, and fit_transform()
?fit()
: learns the parameters (e.g., mean, std)
transform()
: applies the transformation
fit_transform()
: does both in one step
from sklearn.model_selection import GridSearchCV
params = {'n_neighbors': [3, 5, 7]}
grid = GridSearchCV(KNeighborsClassifier(), params, cv=5)
grid.fit(X_train, y_train)
These are the most common real-world questions Python learners ask when working with the most-used libraries in data science. Bookmark this post and share it with your learning buddies!
Comments
Post a Comment
Thanks for your message. We will get back you.