Pandas groupby filter on column, and then plot the results

Question:

I have the following df:

subject_id name day value
1 sld 0 0
1 sld 1 5
1 sld 2 12
1 dsld 0 0
1 dsld 1 -1
2 sld 0 0
2 sld 1 7
2 sld 2 8
2 sld 3 4
2 dsld 0 0

I want to make a line plot with the following criteria:

  1. Group by subject_id
  2. for each group, only take the rows where name == sld
  3. line plot the data where x is the day, and y is the value

I want to plot all the groups on the same plot. Preferably using seaborn

fig, ax = plt.subplots(figsize=(8, 6))
df_sld = df[df['name'] == 'sld']
df_sld.groupby('subject_id').plot(x = 'day', y = 'value', ax = ax)

However, this is taking a long time. Is there a faster way to group by subject_id and then only take the rows where name == sld

I also tried

df.groupby('subject_id')['name'].apply(lambda x: x == 'sld').plot(x = 'day', y = 'value')
df.groupby('subject_id').apply(lambda x: x['name'] == 'sld').plot(x = 'day', y = 'value')

But get an error saying no numerical data

Asked By: Sharhad Bashar

||

Answers:

IIUC,

df.query('name == "sld"').set_index(['day', 'subject_id'])['value'].unstack().plot()

Output:

enter image description here

Answered By: Scott Boston
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.