Advertisement
furas

Pandas - convert data

Jul 24th, 2018
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. def convert(text):
  2.  
  3.     # don't convert if it is not string
  4.     if not isinstance(text, str):
  5.         return text
  6.  
  7.     # don't convert if it is not string
  8.     if 'S[' not in text:
  9.         return text
  10.  
  11.     text = text.split('S[')[1] # split on S[
  12.     #print('string:', text)
  13.  
  14.     text = text[:-1] # remove ] at the end
  15.     #print('string:', text)
  16.  
  17.     parts = text.split(',') # split on ,
  18.     #print('list:', parts)
  19.  
  20.     parts = [x.split('}')[1] for x in parts] # split on } to remove {...}
  21.     #print('list:', parts)
  22.  
  23.     return parts
  24.  
  25. # -------------------
  26.  
  27. data = '''Product code,Options
  28. COWZGH,"{272}Size: S[{854}Newborn (2.5-6kg),{855}Big Baby (6-9kg)]"
  29. PHBC,
  30. ORGWBT0,"{14}Size: S[{49}Newborn (2.5-6kg),{50}Big Baby (6-9kg),{51}Preemie (1.5-2.5kg)]"
  31. COVWDBC,"{270}Size: S[{850}Newborn (2.5-6kg),{851}Big Baby (6-9kg)]"
  32. COVWMV,"{271}Size: S[{852}Newborn (2.5-6kg),{853}Big Baby (6-9kg)]"
  33. BZ-168,
  34. ORWNG,"{200}Size: S[{662}Newborn (2.5-6kg),{663}Big Baby (6-9kg)]"
  35. ORWNB13,"{199}Size: S[{660}Newborn (2.5-6kg),{661}Big Baby (6-9kg)]"
  36. HBCDTG,'''
  37.  
  38. import io
  39. import pandas as pd
  40.  
  41. file_like_object = io.StringIO(data)
  42.  
  43. df = pd.read_csv(file_like_object)
  44.  
  45. print('\n--- before ---\n')
  46. print(df)
  47.  
  48. df['Options'] = df['Options'].apply(convert)
  49.  
  50. print('\n--- after ---\n')
  51. print(df)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement