程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Pandas. Get the index (row index) of the element location according to the condition in the dataframe

編輯:Python

Pandas.DataFrame Get the location of the element according to the condition in index( Row index )

1、 background

In many cases , We want to calculate the value of a column in a specified row , To index the value of another column in that row , For example, the following table :

We want to Type The value in the column Watermelon, obtain Watermelon Row index value of (index), So as to locate quickly Watermelon Line in Price Values in columns .

2、df as follows :

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

3、 The image of the code running result is as follows

3.1、 Output df

print(df)

The output is as follows :

3.2、 Output Watermelon Of index

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

The output is as follows :

3.3、 Output Price In the column ,index be equal to 6 The value of that element

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

The output is as follows :

4、 The complete code is as follows :

4.1、 Code :

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、 Running results :

5、 Another situation


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved