Pandas.DataFrame中根据条件获取元素所在位置的index(行索引)

1、背景

很多情况下,我们想要根据某一列在指定行的数值,来索引另一列在该行的数值,比如下表:

在这里插入图片描述

我们想根据Type列中的值Watermelon,得到Watermelon的行索引值(index),从而快速定位Watermelon所在行在Price列中的取值。

2、df如下:

df = pd.DataFrame({'Type':['Apple', 'Pear', 'Orange', 'Grape', 'Banana', 'Lemon', 'Watermelon', 'Tomato'], 'Price':[25, 10, 15, 30, 12, 15, 30, 20]})

3、代码运行结果图片如下

3.1、输出df

print(df)
输出结果如下:

在这里插入图片描述

3.2、输出Watermelon的index

row_index = df[df.Type == 'Watermelon'].index.tolist()[0]
print(row_index)
输出结果如下:

在这里插入图片描述

3.3、输出Price列中,index等于6的那个元素的值

Watermelon_price = df['Price'][row_index]
print(Watermelon_price)
输出结果如下:

在这里插入图片描述

4、完整代码实现如下:

4.1、代码:

import pandas as pd
df = pd.DataFrame({'Type': ['Apple', 'Pear', 'Orange', 'Grape', 'Banana', 'Lemon', 'Watermelon', 'Tomato'], \
                   'Price': [25, 10, 15, 30, 12, 15, 30, 20]})

print(df)

row_index = df[df.Type == 'Watermelon'].index.tolist()[0]
print(row_index)

Watermelon_price = df['Price'][row_index]
print(Watermelon_price)

4.2、运行结果:

在这里插入图片描述

5、另一种情况

在这里插入图片描述

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐