Pandas Count Unique Occurrences By Month
I have some monthly data that I'm trying to summarize using Pandas and I need to count the number of unique entries that occur each month. Here's some sample code that shows what
Solution 1:
The filling is optional.
In [40]: testFrame.apply(Series.value_counts).fillna(0)
Out[40]:
JAN FEB MAR APR
No Data 1020
Purchased Competitor 1012
purchased Prod 1301
Here is a neat apply trick. I'll create a function and print out what is incoming (and maybe even debug in their). Then easy to see what's happening.
In[20]: deff(x):
....: print(x)
....: returnx.value_counts()
....:
In[21]: testFrame.apply(f)
ApurchasedProdBNoDataCPurchasedCompetitorName: JAN, dtype: objectApurchasedProdBNoDataCPurchasedCompetitorName: JAN, dtype: objectApurchasedProdBpurchasedProdCpurchasedProdName: FEB, dtype: objectANoDataBNoDataCPurchasedCompetitorName: MAR, dtype: objectAPurchasedCompetitorBpurchasedProdCPurchasedCompetitorName: APR, dtype: objectOut[21]:
JANFEBMARAPRNoData1NaN2NaNPurchasedCompetitor1NaN12purchasedProd13NaN1[3 rows x 4 columns]
So its doing this operation then concatting them together (with the correct labels)
In[22]: testFrame.iloc[0].value_counts()
Out[22]:
purchasedProd2PurchasedCompetitor1NoData1dtype: int64
Solution 2:
li = [testFrame.ix[:,i].value_counts() for i in range(len(mnths))]
frame = pd.DataFrame(li, index=mnths)
frame.fillna(value=0).swapaxes(0,1)
Out[42]:
JAN FEB MAR APR
No Data 1 0 2 0
Purchased Competitor 1 0 1 2
purchased Prod 1 3 0 1
[3 rows x 4 columns]
Post a Comment for "Pandas Count Unique Occurrences By Month"