Home > Software engineering >  How to extract rows in pandas dataframe into a dict that corresponds to given time?
How to extract rows in pandas dataframe into a dict that corresponds to given time?

Time:12-08

I have a dataframe df that has columns: id, time, val.

Each id has multiple rows, where each row is sorted according to increasing time. Time is an int. id is also an int. val is a float.

e.g.,

id   time  val
0    1     2.3
0    2     3.0
0    5     8.0
1    1     5.1
1    2     7.8
.......

Given a time t, I need to return a dict that stores id: val pairs at the given t.

e.g., t = 2, return {0: 3.0; 1: 7.8}

I am wondering if there's a built-in way to do this with pandas dataframe?

CodePudding user response:

A possible solution:

dict(df.loc[df.time.eq(2), ['id', 'val']].to_records(index=False))

Another possible solution:

aux = df.loc[df.time.eq(2), ['id', 'val']]
dict(zip(aux.id, aux.val))

Output:

{0: 3.0, 1: 7.8}

CodePudding user response:

You can do:

t = 2
df.loc[df.time.eq(t)].set_index('id')['val'].to_dict()

output:

{0: 3.0, 1: 7.8}

In case you have multiindex i.e. your id and time are both indices.

Then if your index order is ['id', 'time'] then you can do:

t = 2
df1.loc[(slice(None), t), :].reset_index('time')['val'].to_dict()

if your index order is ['time', 'id'] then:

t = 2
df1.loc[(t, slice(None)), :].reset_index('time')['val'].to_dict()

CodePudding user response:

You can use a dict comp

mapping = {k: v.groupby("id")["val"].apply(list).to_dict() for k, v in df.reset_index("time").groupby("time")}
print(mapping.get(2))

Output:

{0: [3.0], 1: [7.8]}
  • Related