Pandas Series and DataFrame: Creation, Indexing, Slicing and Iteration
What this domain tests
The exam checks whether you can build the two Pandas objects from lists, dictionaries and scalars, read their attributes, select data by label and by position, slice rows, iterate, and do aligned arithmetic.
Creation and attributes
pd.Series(data, index=..., name=...)is one-dimensional. A list gets a default RangeIndex 0..n-1; a dictionary's keys become the index.pd.DataFrame(dict_of_lists)turns keys into columns; a list of dictionaries also becomes columns; a dictionary of Series aligns on index labels.- Attributes take no parentheses:
df.shape,df.size,df.index,df.columns,df.dtypes,df.values,df.ndim. Methods do:df.head(),df.info().
Selection, slicing, iteration
df['Marks']returns a Series;df[['Marks','Name']]returns a DataFrame..locis label-based and includes the stop label;.ilocis position-based and excludes the stop position.- Boolean mask:
df[df['Marks'] > 80]. - Iterating a DataFrame yields column names;
df.iterrows()yields(index, row Series); iterating a Series yields values. - Arithmetic aligns on index labels, and unmatched labels produce
NaN.
Worked example
s = pd.Series([10, 20, 30], index=['a','b','c']). Then s['b'] and s.iloc[1] both return 20. s['a':'b'] returns labels a and b, because label slicing is inclusive at both ends. For a DataFrame whose row labels are 0 and 1, df.loc[0:1] returns two rows while df.iloc[0:1] returns only row 0. The reasoning is simple: loc reads labels, iloc counts positions.
Traps that cost marks
Mixing up loc and iloc; writing df.shape(); assuming df['col'] and df[['col']] have the same type; expecting iteration over a DataFrame to give rows; ignoring the NaN created by label misalignment; using chained indexing when assigning a new column.