Pandas Dataframe - Get Index Values Based On Condition
I have a text file called data.txt containing tabular data look like this: PERIOD CHANNELS 1 2 3 4 5 0 1.51 1.61 1.94
Solution 1:
You can add the following code:
Retrieve the index based on the condition. Assumes constant increasing down the channels.
lower_channel_energy = df[df[period]>lower_energy].index[0]
high_channel_energy = df[(df[period]<higher_energy).shift(-1)==False].index[0]
Printing the channels that we calculated:
print("The lower energy channel is {}".format(lower_channel_energy))
print("The higher energy channel is {}".format(high_channel_energy))
This solution assumes that the energy is increasing on the channels going down.
Solution 2:
You can actually read your file directly with Pandas to simplify the program. I can reproduce the output you are expecting with:
import pandas as pd
df = pd.read_csv('data.txt', engine='python' header=1,sep=r'\s{2,}')
period = input('Enter the period: ')
lower_energy = float(input('Enter the lower energy value: '))
higher_energy = float(input('Enter the higher energy value: '))
# select the channels within the ranges provided
lo_e_range = (df[period] > lower_energy)
hi_e_range = (df[period] > higher_energy)
# Indices of the lower and higher energy channels
lec = df[period][lo_e_range].index[0]
hec = df[period][hi_e_range].index[0]
print('The lower energy channel is {}'.format(df['CHANNELS'][lec]))
print('The higher energy channel is {}'.format(df['CHANNELS'][hec]))
I have edited the code to take into account your comment.
Post a Comment for "Pandas Dataframe - Get Index Values Based On Condition"