Reputation: 21
Consider the following series which represents the distance between location a
and locations b
, c
, d
:
a
a 0
b 10
c 12
d 21
Now, what I'm trying to do is retrieve all location names that are within a certain distance from a
.
For example, I would like to print out all variables that are within a 15 unit distance from a
, excluding a
, which would be b
and c
.
b
c
I've tried creating an empty list and then using a for loop to append to that list but to no avail, so I'm obviously missing something.
Upvotes: 0
Views: 73
Reputation: 1413
Try this:
dist = 15
val = list(df.loc[(df['a'] < dist) & (df.index != 'a')].index)
print(val)
Output:
['b', 'c']
Upvotes: 0
Reputation: 93
Forget loops, pandas and numpy already have builtin functions that make the job. In this case you can use np.where.
import pandas as pd
import numpy as np
df = pd.Series({'a':0, 'b':10, 'c':12, 'd':21}, index=['a', 'b', 'c', 'd'])
df.iloc[np.where((df<=15) & (df.index !='a'))]
Upvotes: 1
Reputation: 7614
You can do this, i assumed the first column is an index:
print(df[(df['a'] < 15) & (df.index != 'a')])
a
loc
b 10
c 12
Upvotes: 0