Skip to content

Instantly share code, notes, and snippets.

@DavidLutton
Last active April 3, 2020 10:29
Show Gist options
  • Save DavidLutton/806cc07c63f9735757c31e20e9d7b742 to your computer and use it in GitHub Desktop.
Save DavidLutton/806cc07c63f9735757c31e20e9d7b742 to your computer and use it in GitHub Desktop.
Intended to normalize to dataframe columns to Hz
def get_normalized(df):
"""Normalize frequencies (MHz, GHz) in a DataFrame to Hz."""
SI_PREFIXES = 'yzafpnum kMGTPEZY'
SI_SCALE_FACTOR = dict([(key, 10**((-8+i)*3)) for i, key in enumerate(SI_PREFIXES)])
for column in df:
xHz = [ r for r in re.split(r'[\(*\)]', column) if r not in ''][-1]
# find eg 'MHz' from the column name 'Frequency (MHz)'
if xHz[-2:] == 'Hz' and len(xHz) == 3: # check is both ends 'Hz' and has length to be a prefix
to = column[:-5] + '(Hz)' # get column label without (?Hz) and append '(Hz)'
df = df.rename(columns={column: to}) # rename
df[to] = SI_SCALE_FACTOR[xHz[0]]*df[to] # scale to Hz
# consider rounding to ~ 8 decimal places to cut off multiplication errors
return df
s = "Frequency of ... (GHz)"
d = 9.87654321123456
SI_PREFIXES = 'yzafpnum kMGTPEZY'
SI_SCALE_FACTOR = dict([(key, 10**((-8+i)*3)) for i, key in enumerate(SI_PREFIXES)])
e = [ r for r in re.split(r'[\(*\)]', s) if r not in ''][-1]
prefix = e[0]
if e[-2:] == 'Hz' and len(e) == 3:
print(SI_SCALE_FACTOR[prefix]*d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment