我不能使用pandas loc函数,但是iloc可以工作。
我的代码:
import geopandas as gpd
import pandas as pd
gdf=gpd.read_file('')
df=pd.DataFrame(gdf)
df.head()
df.loc['gid']
遇到错误:
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'
在处理上述异常期间,发生了另一个异常:
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'
有人知道如何解决此错误吗?
答案 0 :(得分:1)
尝试使用它(假设“ gid”是数据框中的一列)
df.loc[df['gid']]
但是,这将返回整个数据帧,因为您正在选择整个列且未定义任何条件。 您可以使用类似这样的东西
df.loc[df['gid']=='abc'] #'abc' being the content of the columns
答案 1 :(得分:0)
loc和iloc服务器有两个不同的用途。 loc通过索引 label 获取行或列。然后,iloc使用索引 positions 进行索引,该索引通常是整数。 loc结构化:
df.loc['row', 'column']
如果'gid'是列的名称,但是您将其传递给loc就像它是行的名称一样,那么最终会出现KeyError。相反,您需要指定要该列的所有行:
df.loc[:, 'gid']
或者直接通过名称直接指定列:
df['gid']
例如:
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
但是没有称为“类型”的行,所以:
>> df.loc['Type']
KeyError: 'Type'