How to get Python to gracefully format None and non-existing fields [duplicate]

The recommendation in PEP 3101 is to subclass Formatter: import string class PartialFormatter(string.Formatter): def __init__(self, missing=’~~’, bad_fmt=”!!”): self.missing, self.bad_fmt=missing, bad_fmt def get_field(self, field_name, args, kwargs): # Handle a key not found try: val=super(PartialFormatter, self).get_field(field_name, args, kwargs) # Python 3, ‘super().get_field(field_name, args, kwargs)’ works except (KeyError, AttributeError): val=None,field_name return val def format_field(self, value, spec): # handle … Read more

Fill missing dates by group

tidyr::complete() fills missing values add id and date as the columns (…) to expand for library(tidyverse) complete(dat, id, date) # A tibble: 16 x 3 id date value <dbl> <date> <dbl> 1 1.00 2017-01-01 30.0 2 1.00 2017-02-01 30.0 3 1.00 2017-03-01 NA 4 1.00 2017-04-01 25.0 5 2.00 2017-01-01 NA 6 2.00 2017-02-01 25.0 … Read more

Format string unused named arguments [duplicate]

If you are using Python 3.2+, use can use str.format_map(). For bond, bond: from collections import defaultdict ‘{bond}, {james} {bond}’.format_map(defaultdict(str, bond=’bond’)) Result: ‘bond, bond’ For bond, {james} bond: class SafeDict(dict): def __missing__(self, key): return ‘{‘ + key + ‘}’ ‘{bond}, {james} {bond}’.format_map(SafeDict(bond=’bond’)) Result: ‘bond, {james} bond’ In Python 2.6/2.7 For bond, bond: from collections import … Read more

Reading multiple files and calculating mean based on user input

So, you can simulate your situation like this; # Simulate some data: # Create 332 data frames set.seed(1) df.list<-replicate(332,data.frame(sulfate=rnorm(100),nitrate=rnorm(100)),simplify=FALSE) # Generate names like 001.csv and 010.csv file.names<-paste0(‘specdata/’,sprintf(‘%03d’,1:332),’.csv’) # Write them to disk invisible(mapply(write.csv,df.list,file.names)) And here is a function that would read those files: pollutantmean <- function(directory, pollutant, id = 1:332) { file.names <- list.files(directory) file.numbers … Read more