Skip to main content
 首页 » 编程设计

python之如何按列值选择行索引

2025年05月04日20luoye11

我在 python 中使用 Dataframe 并尝试根据多个列值选择行索引。下面是我的数据框第 100 行的值:

>>> df.loc[100] 
id                                       100 
iid     9cdb7709-38f8-442a-812a-986b5b148161 
lat                                 -37.8294 
lon                                  144.979 
name                      Doryanthes excelsa 
Name: 100, dtype: object 

我想通过以下命令选择 id 为 100 且 lat 为 -37.8294 的行:

>>> df[(df['id'] == 100) & (df['lat'] == -37.8294)].index 
Int64Index([], dtype='int64') 

上述命令返回一个空索引。我不明白我可以通过 df.loc[100] 命令获取值,但为什么我不能从上述命令获取行索引?

请您参考如下方法:

你想要选择float,但是存在精度问题,所以没有匹配并返回空数据帧

所以需要numpy.isclose :

df1 = df[(df['id'] == 100) & (np.isclose(df['lat'],-37.8294))] 

示例:

df = pd.DataFrame({'id':[100,200], 
                   'lat':[-37.82940007,-37.82]}) 
print (df) 
    id      lat 
0  100 -37.8294 
1  200 -37.8200 
 
df1 = df[(df['id'] == 100) & (df['lat'] == -37.8294)] 
print (df1) 
Empty DataFrame 
Columns: [id, lat] 
Index: [] 
 
df1 = df[(df['id'] == 100) & (np.isclose(df['lat'],-37.8294))] 
print (df1) 
    id      lat 
0  100 -37.8294