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、另一種情況
