Error: in selecting Specific Rows and Column in Data Frame
Created 3 years ago
128
Views
2
Comments
Write a Pandas program to select the specified columns and rows from a given DataFrame.
Select 'name' and 'score' columns in rows 1, 3, 5, 6 from the following data frame.
Sample DataFrame:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',i','j']
df = pd.DataFrame(exam_data , index=labels)
print("Select specific columns and rows:")
print(df.loc[[1, 3, 5, 6], [1, 3]])
Error
Traceback (most recent call last):
File "/tmp/sessions/a7aaf5eadafd6aab/main.py", line 12, in <module>
print(df.loc[[1, 3, 5, 6], [1, 3]])
File "/usr/local/lib/python3.9/dist-packages/pandas/core/indexing.py", line 925, in __getitem__
return self._getitem_tuple(key)
File "/usr/local/lib/python3.9/dist-packages/pandas/core/indexing.py", line 1107, in _getitem_tuple
return self._multi_take(tup)
File "/usr/local/lib/python3.9/dist-packages/pandas/core/indexing.py", line 1059, in _multi_take
d = {
File "/usr/local/lib/python3.9/dist-packages/pandas/core/indexing.py", line 1060, in <dictcomp>
axis: self._get_listlike_indexer(key, axis)
File "/usr/local/lib/python3.9/dist-packages/pandas/core/indexing.py", line 1314, in _get_listlike_indexer
self._validate_read_indexer(keyarr, indexer, axis)
File "/usr/local/lib/python3.9/dist-packages/pandas/core/indexing.py", line 1374, in _validate_read_indexer
raise KeyError(f"None of [{key}] are in the [{axis_name}]")
KeyError: "None of [Int64Index([1, 3, 5, 6], dtype='int64')] are in the [index]"
I need to select a specific column and rows from the given data frame, I am facing key errors like above can anyone help regarding this