Reputation: 7951
I have a dataframe with this structure:
custid province year features... label
123 AB 2005 ... 0
124 ON 2006 ... 1
...
999 QC 2012 ... 1
The last column is the label / target.
I have a lambda function:
def churn_per_feature(x):
d = {}
d['churn_count'] = (x['label'] == 1).sum()
d['cust_count'] = x['custid'].nunique()
d['churn_rate'] = d['churn_count'] / float(d['cust_count'])
return pd.Series(d, index = ['churn_count', 'cust_count', 'churn_rate'])
I have a grouping for two variables, province
and year
:
churn_per_province_year = df.groupby(['province', 'year']).apply(churn_per_feature)
I am attempting to pyplot
this, a single chart with lines, where the x-axis is the years
and each line represents the province
(so far I am only selecting 4 province with biggest customer count, so it's not in a loop):
plt.plot(years, churn_per_province_year[churn_per_province_year['province'] == 'ON']['cust_count'])
plt.plot(years, churn_per_province_year[churn_per_province_year['province'] == 'AB']['cust_count'])
plt.plot(years, churn_per_province_year[churn_per_province_year['province'] == 'BC']['cust_count'])
plt.plot(years, churn_per_province_year[churn_per_province_year['province'] == 'QC']['cust_count'])
plt.show()
I don't know how to reference the years
part.
Upvotes: 1
Views: 334
Reputation: 23139
Do you want something like the following?
df.groupby(['year', 'province']).apply(churn_per_feature)['cust_count'].unstack().plot(legend=True)
With matplotlib plt.plot()
:
churn_per_province_year = df.groupby(['year', 'province']).apply(churn_per_feature).reset_index()
#from matplotlib import pyplot
#years = range(2005, 2019) # add the right range here
plt.plot(years, churn_per_province_year[churn_per_province_year['province'] == 'ON']['cust_count'], label='ON')
plt.plot(years, churn_per_province_year[churn_per_province_year['province'] == 'AB']['cust_count'], label='AB')
plt.plot(years, churn_per_province_year[churn_per_province_year['province'] == 'QC']['cust_count'], label='QC')
plt.legend()
plt.show()
Upvotes: 1