Skip to content

Instantly share code, notes, and snippets.

@jj-github-jj
Last active December 27, 2021 04:47
Show Gist options
  • Save jj-github-jj/a8a683b51aba85fa0f58d9e6e2054951 to your computer and use it in GitHub Desktop.
Save jj-github-jj/a8a683b51aba85fa0f58d9e6e2054951 to your computer and use it in GitHub Desktop.
numeric pandas
def my_float(s):
""" bug in python cant convert -12,345.0 to float so use this workaround
"""
return (float(s.replace(",","")))
#show large nubmers with commas pandas dataframe
# column is string column name
df[column] = df.apply(lambda x: "{:,}".format(x[column]), axis=1)
#split number units string
#from ://stackoverflow.com/questions/2240303/separate-number-from-unit-in-a-string-in-python
def split_units(value):
"""
>>> split_units("2GB")
(2.0, 'GB')
>>> split_units("17 ft")
(17.0, 'ft')
>>> split_units(" 3.4e-27 frobnitzem ")
(3.4e-27, 'frobnitzem')
>>> split_units("9001")
(9001.0, '')
>>> split_units("spam sandwhiches")
(0, 'spam sandwhiches')
>>> split_units("")
(0, '')
"""
units = ""
number = 0
while value: #while string is not empty
try:
number = float(value) #see if conversion to float works now initially no units
break
except ValueError:
units = value[-1:] + units #append last character from string
value = value[:-1] #truncate string stripping last character
return number, units.strip()
def range_to_list(range_string,seperator='-'):
"""
"1kb-2GB" ==> ((1.0,"kb"), (2.0,"GB"))
"""
range_list=range_string.split(sep=seperator)
start=split_units(range_list[0])
end=split_units(range_list[1])
return (start,end)
def split_df_range_column(df_r,c,c1,c2,c3,c4):
""" column c of dataframe containing range string with units is split into c1 thru c4
range is "1.0GHz-2.5GHz" type strings in column c
c1 float c2 string units c3 float c4 string units
c1 : 1.0 c2 : "GHz" ...
"""
for x in [c1,c2,c3,c4]:
df_r[x]=[0.0]*len(df_r)
for index,row in df_r.iterrows():
#print (range_to_list(row['LO_Range']))
r=range_to_list(row[c])
df_r[c1][index]=r[0][0];df_r[c2][index]=r[0][1]
df_r[c3][index]=r[1][0];df_r[c4][index]=r[1][1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment