0

My dataframe consists of the following table:

Time X Y 0100 5 9 0200 7 10 0300 11 12 0400 3 13 0500 4 14 

My goal is to find the index of the value of Y which corresponds to a certain number (e.g.: 9) and return the corresponding X value from the table.

My idea previously was for a for-loop (as I have a number of Ys) to loop through and find all the values which match and then to create an empty array to store the values of X as such:

for i in (list of Ys): empty_storing_array.append(df[index_of_X].loc[df[Y] == i]) 

Problem is (if my newbie understanding of Pandas holds true), the values that loc gives is no number, but rather something else. How should I do it so that empty_storing_array then lists the numbers of X which corresponds to the values in array Y?

3
  • 1
    Is it always a 1-1 relationship? If it is, just set_index to Y and use loc: df.set_index('Y').loc[9, 'X'] Commented May 20, 2019 at 19:44
  • 1
    check .loc and bool slice Commented May 20, 2019 at 19:47
  • @user3483203 No, there is no 1-1 relationship, the sizes of both columns are different Commented May 21, 2019 at 13:48

3 Answers 3

1

you can use df.loc and then ask for the index explicitly. This will return an array, so we slice the first item to get the integer:

df.loc[df['Y']==9, 'X'].index.values[0] 
Sign up to request clarification or add additional context in comments.

Comments

1

try with this :

list_Ys = [9,8,15] #example new_df = df[df['Y'].isin(list_Ys)]['X'] 

the isin method tells whether each element in the DataFrame is contained in values.

if you want to convert your resulting dataframe to an array

new_df.values 

Comments

0

If you need to have a way to retrieve which Y corresponds to a given X then keep both X and Y:

df.loc[df['Y'].isin(list_of_ys), ['Y', 'X']].values 

Perhaps create a dictionary that puts all the Xs corresponding to a Y in a tuple and make the Y the keys.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.