clstaudt
clstaudt

Reputation: 22438

Short form of this pandas select statement

benchmarks[(benchmarks["Region"] == "EU") & (benchmarks["Channel"] == "Email") & (benchmarks["Metric"] == "Unique Open Rate")]["Benchmark"][0]

In the dataframe benchmarks, ("Region", "Channel", "Metric") is a unique key for the value in the column "Benchmark". This pandas statement therefore yields one number. It's very clear but also quite a line to type for such a simple selection - is there a short form?

Upvotes: 1

Views: 110

Answers (1)

jezrael
jezrael

Reputation: 862541

I think yes, if you use query:

q = "Region == 'EU' & Channel == 'Email' & Metric == 'Unique Open Rate'"
benchmarks.query(q)["Benchmark"][0]

Sample:

benchmarks = pd.DataFrame({'Region':['EU','USA'],
                           'Channel':['Email','Text'],
                           'Metric':['Unique Open Rate','Rate'],
                           'Benchmark':[5,2]})
print (benchmarks)
   Benchmark Channel            Metric Region
0          5   Email  Unique Open Rate     EU
1          2    Text              Rate    USA

q = "Region == 'EU' & Channel == 'Email' & Metric == 'Unique Open Rate'"
a = benchmarks.query(q)["Benchmark"][0]
print (a)
5

Upvotes: 2

Related Questions