Help Mohan for displaying a column of a DataFrame 'DF' as he is confused among the following options.
(A) DF.loc['COLUMN NAME']
(B) DF[COLUMN NAME]
(C) DF.COLUMN NAME
(D) DF['COLUMN NAME']
Help Mohan for displaying a column of a DataFrame 'DF' as he is confused among the following options.
(A) DF.loc['COLUMN NAME']
(B) DF[COLUMN NAME]
(C) DF.COLUMN NAME
(D) DF['COLUMN NAME']
Solution
A column of a DataFrame can be displayed by putting its name in quotes inside square brackets, , as in (D). It can also be displayed with dot notation, , as in (C). Dot notation works only when the column name is a valid identifier, with no spaces or special characters.
Option (A): takes a row label first, so looks for a row with that name and not a column.
Option (B): without quotes, Python treats COLUMN NAME as a variable name, which raises a NameError.
Use quotes with square brackets whenever the column name has spaces or clashes with a DataFrame method or attribute.
Related questions:
2026: 21 May Shift 1
2025: 14 May Shift 1
2026: 24 May Shift 1