loc with label slicing on a DataFrame?import pandas as pd df = pd.DataFrame({ 'A': [10, 20, 30, 40], 'B': [1, 2, 3, 4] }, index=['a', 'b', 'c', 'd']) result = df.loc['b':'d', 'A'] print(result)
loc includes the end label in slicing.The loc indexer uses labels and includes the last label in slicing. Here, slicing from 'b' to 'd' includes rows with labels 'b', 'c', and 'd'.
iloc with integer slicing on a DataFrame?import pandas as pd df = pd.DataFrame({ 'A': [10, 20, 30, 40], 'B': [1, 2, 3, 4] }, index=['a', 'b', 'c', 'd']) result = df.iloc[1:3, 0] print(result)
iloc uses integer positions and excludes the end index in slicing.The iloc indexer uses integer positions and excludes the last index in slicing. Here, rows at positions 1 and 2 are selected, which correspond to labels 'b' and 'c'.
df.loc[2:4, 'X'] and df.iloc[2:4, 0]?import pandas as pd df = pd.DataFrame({ 'X': [100, 200, 300, 400, 500], 'Y': [5, 4, 3, 2, 1] }, index=[1, 2, 3, 4, 5]) loc_result = df.loc[2:4, 'X'] iloc_result = df.iloc[2:4, 0] print('loc_result:\n', loc_result) print('iloc_result:\n', iloc_result)
loc uses labels and includes the end label, while iloc uses integer positions and excludes the end index.loc[2:4] selects rows with labels 2, 3, and 4. iloc[2:4] selects rows at integer positions 2 and 3, which correspond to labels 3 and 4.
import pandas as pd df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6] }, index=[10, 20, 30]) result = df.loc[1] print(result)
The DataFrame index labels are 10, 20, 30. Using loc[1] looks for label 1, which does not exist, causing a KeyError.
df with a date index from '2023-01-01' to '2023-01-10'. You want to select data from '2023-01-03' to '2023-01-06'. Which option correctly selects these rows?import pandas as pd dates = pd.date_range('2023-01-01', '2023-01-10') df = pd.DataFrame({'value': range(10)}, index=dates) # Select rows here
loc uses labels (dates here), and iloc uses integer positions.loc selects rows by label, so slicing with date strings works. iloc expects integer positions, so slicing with date strings causes an error.
