3 ms·
My favorite, most elegant SO answer I've ever gotten was to a question about Pandas. The question was "How do I create a column where each row's value is the m
by staticautomatic 7y ago
My favorite, most elegant SO answer I've ever gotten was to a question about Pandas.
The question was "How do I create a column where each row's value is the mean of another column's values starting at that row?" The answer was:
df.loc[::-1, 'col_1'].expanding().mean()[::-1]
- maest 7y agoI guess elegance is in the eye of the beholder. Separately, I find it upsetting there are at least 6 ways of reversing a dataframe. It suggests some API smell.
- staticautomatic 7y agoI get tripped up by the Pandas API no matter how often I use it, and when I haven't used it in a while I practically have to re-learn all the basics. But whenever it does exactly what I need in a readable one-liner, I forgive it for all its transgressions. It's an abusive relationship.
- bobbylarrybobby 7y agoI dunno about elegant... seems like pandas is missing a reverse parameter in expanding. Surely this would be preferable: df[col].expanding(reverse=True).mean()