Which of the following are the correct commands to change the name of a row in a DataFrame 'df1'?
(A) df1.rename({old name:new name},axis='rows',inplace=True)
(B) df1.rename({old name:new name},axis=0,inplace=True)
(C) df1.rename({old name:new name},axis='index',inplace=True)
(D) df1=df1.rename({old name:new name},axis='rows',inplace=True)
Which of the following are the correct commands to change the name of a row in a DataFrame 'df1'?
(A) df1.rename({old name:new name},axis='rows',inplace=True)
(B) df1.rename({old name:new name},axis=0,inplace=True)
(C) df1.rename({old name:new name},axis='index',inplace=True)
(D) df1=df1.rename({old name:new name},axis='rows',inplace=True)
Solution
In pandas, the axis argument of rename() accepts 0 or 'index' for rows, and 1 or 'columns' for columns. So (B) axis=0 and (C) axis='index' both correctly rename a row label.
(A) and (D): 'rows' is not a valid axis name in rename() and raises a ValueError. (D) has a second error: with inplace=True, rename() returns None, so df1= would overwrite the DataFrame with None.
Alternatively, df1.rename(index={old name:new name}, inplace=True) also renames a row.
Related questions:
2025: 13 May Shift 2
2026: 18 May Shift 2
2026: 21 May Shift 1