我不能使用熊猫loc功能,但是loc可以工作。
我的代码:
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'有人知道我怎么纠正这个错误吗?
发布于 2019-08-27 04:46:56
尝试使用此方法(假设'gid‘是dataframe中的一个列)
df.loc[df['gid']]但是,这将返回整个dataframe,因为您正在选择整个列&而不是定义任何条件。你可以用这样的东西
df.loc[df['gid']=='abc'] #'abc' being the content of the columns 发布于 2019-12-10 20:26:07
loc和iloc服务器有两个不同的用途。loc通过索引标签获取行或列。iloc然后使用索引位置,这很大程度上是一个整数。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'https://stackoverflow.com/questions/57667753
复制相似问题