Pandas: groupby forward fill with datetime index

One way is to use the transform function to fill the value column after group by: import pandas as pd a[‘value’] = a.groupby(‘company’)[‘value’].transform(lambda v: v.ffill()) a # company value #level_1 #2010-01-01 a 1.0 #2010-01-01 b 12.0 #2011-01-01 a 2.0 #2011-01-01 b 12.0 #2012-01-01 a 2.0 #2012-01-01 b 14.0 To compare, the original data frame looks … Read more

Leaving values blank if not passed in str.format

You can follow the recommendation in PEP 3101 and use a subclass Formatter: import string class BlankFormatter(string.Formatter): def __init__(self, default=””): self.default=default def get_value(self, key, args, kwds): if isinstance(key, str): return kwds.get(key, self.default) else: return string.Formatter.get_value(key, args, kwds) kwargs = {“name”: “mark”, “adj”: “mad”} fmt=BlankFormatter() print fmt.format(“My name is {name} and I’m really {adj}.”, **kwargs) # … Read more

Convert NA into a factor level

You can use addNA(). x <- c(1, 1, 2, 2, 3, NA) addNA(x) # [1] 1 1 2 2 3 <NA> # Levels: 1 2 3 <NA> This is basically a convenience function for factoring with exclude = NULL. From help(factor) – addNA modifies a factor by turning NA into an extra level (so that … Read more