Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. import pandas as pd
  2.  
  3. df = pd.DataFrame([[' a ', 10], [' c ', 5]])
  4.  
  5. df.replace('^s+', '', regex=True, inplace=True) #front
  6. df.replace('s+$', '', regex=True, inplace=True) #end
  7.  
  8. df.values
  9.  
  10. df_obj = df.select_dtypes(['object'])
  11. print (df_obj)
  12. 0 a
  13. 1 c
  14.  
  15. df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())
  16. print (df)
  17.  
  18. 0 1
  19. 0 a 10
  20. 1 c 5
  21.  
  22. df[0] = df[0].str.strip()
  23.  
  24. >>> df = pd.DataFrame([[' a ', 10], [' c ', 5]])
  25. >>> df[0][0]
  26. ' a '
  27. >>> df[0] = df[0].apply(lambda x: x.strip())
  28. >>> df[0][0]
  29. 'a'
  30.  
  31. >>> df = pd.DataFrame([[' a ', 10], [' c ', 5]])
  32. >>> df.apply(lambda x: x.apply(lambda y: y.strip() if type(y) == type('') else y), axis=0)
  33.  
  34. 0 1
  35. 0 a 10
  36. 1 c 5
  37.  
  38. >>> df.replace('(^s+|s+$)', '', regex=True, inplace=True)
  39. >>> df
  40. 0 1
  41. 0 a 10
  42. 1 c 5
  43.  
  44. >>> df[0] = df[0].str.strip()
  45.  
  46. df[0] = df[0].str.strip()
  47.  
  48. non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
  49. df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())
  50.  
  51. df.applymap(lambda x: x.strip() if type(x) is str else x)
  52.  
  53. import pandas as pd
  54.  
  55.  
  56. def trimAllColumns(df):
  57. """
  58. Trim whitespace from ends of each value across all series in dataframe
  59. """
  60. trimStrings = lambda x: x.strip() if type(x) is str else x
  61. return df.applymap(trimStrings)
  62.  
  63.  
  64. # simple example of trimming whitespace from data elements
  65. df = pd.DataFrame([[' a ', 10], [' c ', 5]])
  66. df = trimAllColumns(df)
  67. print(df)
  68.  
  69.  
  70. >>>
  71. 0 1
  72. 0 a 10
  73. 1 c 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement