简体   繁体   中英

I can't use the pandas loc function but iloc works

I can't use the pandas loc function but iloc works.

My code:

import geopandas as gpd
import pandas as pd

gdf=gpd.read_file('')
df=pd.DataFrame(gdf)
df.head()
df.loc['gid']

Getting error:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2656             try:
-> 2657                 return self._engine.get_loc(key)
   2658             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()

KeyError: 'gid'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
5 frames
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2657                 return self._engine.get_loc(key)
   2658             except KeyError:
-> 2659                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2660         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2661         if indexer.ndim > 1 or indexer.size > 1:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()

>KeyError: 'gid'

Has somebody idea how can I fix this error?

Try using this (assuming 'gid' is a column in the dataframe)

df.loc[df['gid']]

However, this will return the entire dataframe because you are selecting the whole column & not defining any conditions. You can use something this like this

df.loc[df['gid']=='abc'] #'abc' being the content of the columns 

loc and iloc server two different purposes. loc gets rows or columns by index label . iloc gets then using index positions which much be an integer. loc is structured:

df.loc['row', 'column']

If 'gid' is the name of a column, but you're passing it to loc as if it was the name of a row, then you end up with a KeyError. Instead, you need to either specify you want all rows for that column:

df.loc[:, 'gid']

Or just specify the column directly by name:

df['gid']

For example:

import pandas as pd

df = pd.DataFrame({'Type': ['fruit', 'fruit', 'vegetable'],
                   'Color': ['Red', 'Orange', 'Yellow'],
                   'Quantity': [4, 8, 2]
                   },
                  index=['apple', 'orange', 'bell pepper'])
print(df)  

                  Type   Color  Quantity
apple            fruit     Red         4
orange           fruit  Orange         8
bell pepper  vegetable  Yellow         2

>> df.loc[:, 'Type']  

apple              fruit
orange             fruit
bell pepper    vegetable
Name: Type, dtype: object

>> df['Type']  

apple              fruit
orange             fruit
bell pepper    vegetable

>> df.loc['apple']

Type        fruit
Color         Red
Quantity        4

But there's not a row called 'Type' so:

>> df.loc['Type']

KeyError: 'Type'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM