Pandas.DataFrame中根据条件获取元素所在位置的index(行索引)
3、代码运行结果图片如下3.1、输出df输出结果如下:输出结果如下:输出结果如下:4.2、运行结果:
·
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、另一种情况
更多推荐
已为社区贡献3条内容
所有评论(0)