Home > Mobile >  Getting a specific value inside dataframe and the position
Getting a specific value inside dataframe and the position

Time:10-02

I have a Dataframe similar to the tabel example here, and I want to find a specific value inside this Dataframe, for example the value 2. Herefor i use np.where, in the next step I want to check if there is a next value, and if so is the value smaller/bigger/similar. My solution would be 'print out the np.where and hardcode the index with [-x] for each value after the 2.' So iam looking for a smarter Solution for cases with for example 100 Values

The output should be: 2 is bigger ,2 is smaller ,2 is the last number.

Value
1
2
1
2
3
2

CodePudding user response:

If I understand your question correctly you could try this code

import pandas as pd

frame = pd.DataFrame([1, 2, 1, 2, 3, 2], columns=['num'])

def find_values(df, number):
    for index, row in df.iterrows():
        if row['num'] == number:
            if len(df) == index 1:
                print(number, 'is the last number')
            else:
                next_num = df.loc[index 1, 'num']
                if next_num > number:
                    print(number, '<', next_num)
                elif next_num < number:
                    print(number, '>', next_num)
                else:
                    print(number, '==', number)

find_values(frame, 2)

output:

2 > 1
2 < 3
2 is the last number
  • Related