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

标签 python pandas

我在 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

关于python - 如何按列值选择行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46155462/

相关文章:

python - NameError : name 'DEFAULT_STRING' is not defined

python - 我写这段代码是为了在 5 个等级中取平均值并根据平均值显示一条消息,它正在运行

python - 在 python 3.x 版本中使用 matplotlib 时不显示任何内容

python - True 值的行和列索引

python - 无法返回整个 CSV 数据框

python - Pandas 数据透视表和 Matplotlib 栏

python - 使用柏林噪声按程序生成海拔明显较高的区域

python - Tensorflow CIELAB 颜色空间边界

Python:我使用 .decode() - 'ascii' 编解码器无法编码

python - Pandas Python 写入现有文件并匹配列值