Anthony W
Anthony W

Reputation: 1327

List comprehension from pandas dataframe

I have a dataframe with dates, times and values

Date       Time Value
2017-01-05 1730 893
2017-01-05 1700 990
2017-01-05 1600 801
2017-02-01 1700 701
2017-02-01 1800 774

I want to build a list comprehension that takes date + time as a key to return specific values. So for example:

Date = 2017-01-05, Time = 1600 gives Value 801
Date = 2017-02-01, Time = 1800 gives Value 774

The following code sort of works - apart from the fact that I'm left with an ugly array type in my list:

valueList =[]

for d, t in df:
    valueList.append(df[(df['Date'] == d) & (df['Time'] == t)].Value.values)

But I'd really like to do is generate a list of selected values using a list comprehension.

Upvotes: 0

Views: 1363

Answers (1)

jpp
jpp

Reputation: 164643

Don't overcomplicate the problem. A list comprehension does not have keys, so you cannot use it for a mapping. You can, however, use a pd.Series or dict object.

You can simply create a series with your index as ['Date', 'Time']:

s = df.set_index(['Date', 'Time'])['Value']

print(s.get(('2017-02-01', 1700)))
# 701

If you need a dictionary:

d = s.to_dict()

In either case, you can access a value given a date and time directly.

Upvotes: 3

Related Questions