SharpObject
SharpObject

Reputation: 607

Dataframe with column of ranges. Given number, select row where number occurs

I have a dataframe with a column of a range of numbers, and then more columns of data

[1, 2, 3, ..., 10]    | a | b 
[11, 12, 13, 14, ...] | c | d  

Given a number like 10, 14, etc. how do I select the row where that number is in the range, i.e for 10 I want [1, 2, 3, ..., 10] | a | b row to be returned.

So far Ive tried dfs['A'].ix[10 in dfs['A']['B']] where dfs is a dictionary of dataframes, 'A' is a dataframe, 'B' is the column with ranges.

How do I do this?

Upvotes: 0

Views: 64

Answers (2)

andrew
andrew

Reputation: 4089

df = pd.DataFrame({'ranges':[range(11), range(11,20)], 'dat1':['a','c'], 'dat2':['b','d']})
mask = df.ranges.apply(lambda x: 10 in x)
df.ix[mask]

Upvotes: 1

akuiper
akuiper

Reputation: 214967

Use apply to loop through column B and check each element individually which returns a logical index for subsetting:

df = pd.DataFrame({"B": [list(range(1,11)), list(range(11,21))], "col1":["a", "b"], "col2":["c", "d"]})

df[df["B"].apply(lambda x: 10 in x)]

#                                 B   col1  col2
# 0 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]      a     c

Upvotes: 1

Related Questions