1
votes
print(first3.loc[:3, ['STNAME']])

This should return the first 3 elements of the STNAME column in the first3 dataframe... however this is not happening, I am receiving an error instead.. I can't understand why.

This is the error I am receiving:

File "/Users/....", line 1472, in getitem return self._getitem_tuple(key) File "/Users/....", line 890, in _getitem_tuple retval = getattr(retval, self.name)._getitem_axis(key, axis=i) File "/Users/....", line 1866, in _getitem_axis return self._get_slice_axis(key, axis=axis) File "/Users/....", line 1511, in _get_slice_axis slice_obj.step, kind=self.name) File "/Users/....", line 4107, in slice_indexer kind=kind) File "/Users/....", line 4314, in slice_locs end_slice = self.get_slice_bound(end, 'right', kind) File "/Users/....", line 4244, in get_slice_bound raise err KeyError: 3

and here is the first3:

            STNAME      POPTOT

191 California 15924150.0 2567 Texas 8269632.0 609 Illinois 6815061.0 1861 New York 6321295.0 330 Florida 5564635.0 99 Arizona 5173150.0 1254 Michigan 3863924.0 2283 Pennsylvania 3549228.0 3001 Washington 3439809.0 2079 Ohio 3245910.0 1239 Massachusetts 3044796.0 315 Connecticut 2673320.0 1214 Maryland 2640226.0 1805 New Jersey 2498943.0 1776 Nevada 2427950.0 398 Georgia 2417795.0 1924 North Carolina 2309027.0 1338 Minnesota 2059617.0 1509 Missouri 2033597.0 2471 Tennessee 1986551.0 2867 Virginia 1921722.0 2822 Utah 1852698.0 3097 Wisconsin 1825699.0 250 Colorado 1794424.0 712 Indiana 1754727.0 2246 Oregon 1641036.0 2168 Oklahoma 1577791.0 1 Alabama 1406269.0 558 Hawaii 1293120.0 905 Kansas 1220478.0 1132 Louisiana 1216552.0 1011 Kentucky 1196619.0 2357 South Carolina 1185938.0 1827 New Mexico 1015967.0 1682 Nebraska 961357.0 2351 Rhode Island 919804.0 324 Delaware 897934.0 1794 New Hampshire 842389.0 115 Arkansas 807152.0 805 Iowa 807090.0 564 Idaho 719782.0 1197 Maine 632728.0 328 District of Columbia 601723.0 1426 Mississippi 593642.0 69 Alaska 478402.0 3041 West Virginia 393551.0 1625 Montana 348199.0 2404 South Dakota 315244.0 2025 North Dakota 297947.0 2852 Vermont 277721.0 3170 Wyoming 213321.0

1
Can you post what first3 is and what error you get?rafaelc

1 Answers

0
votes

The reason why you are probably receiving errors is that you are using number as your indexer, where your indexes are not numbers (they are probably labeled).

You can do this in three different ways:

  • loc: first3.loc[:'labeled_third_index', 'STNAME']

  • iloc: first3.iloc[:3, 1] #assuming that 1 is the index for 'STNAME'

  • ix: first3.ix[:3, 'STNAME'] #depracatted