Advertisement
Guest User

Untitled

a guest
Nov 13th, 2015
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. #!/usr/bin/env python2.7
  2.  
  3. import pandas as pd
  4.  
  5. class SinkInto(object):
  6. def __init__(self, function, *args, **kwargs):
  7. self.args = args
  8. self.kwargs = kwargs
  9. self.function = function
  10.  
  11. def __rrshift__(self, other):
  12. return self.function(other, *self.args, **self.kwargs)
  13.  
  14. def __repr__(self):
  15. return "<SinkInto {} args={} kwargs={}>".format(
  16. self.function,
  17. self.args,
  18. self.kwargs
  19. )
  20.  
  21.  
  22. def pipe(original):
  23. class PipeInto(object):
  24. function = original
  25.  
  26. def __init__(self, *args, **kwargs):
  27. self.args = args
  28. self.kwargs = kwargs
  29.  
  30. def __rrshift__(self, other):
  31. return self.function(other, *self.args, **self.kwargs)
  32.  
  33. def __repr__(self):
  34. return "<SinkInto {} args={} kwargs={}>".format(
  35. self.function,
  36. self.args,
  37. self.kwargs
  38. )
  39. return PipeInto
  40.  
  41.  
  42. @pipe
  43. def select(df, *args):
  44. cols = [x for x in args]
  45. return df[cols]
  46.  
  47.  
  48. @pipe
  49. def rename(df, **kwargs):
  50. for name, value in kwargs.items():
  51. df = df.rename(columns={'%s' % name: '%s' % value})
  52. return df
  53.  
  54.  
  55. df = pd.DataFrame({'one' : [1., 2., 3., 4., 4.],
  56. 'two' : [4., 3., 2., 1., 3.]})
  57.  
  58. df >> select('one') >> rename(one='first')
  59.  
  60. # Output
  61. Traceback (most recent call last):
  62. File "decorator_test.py", line 58, in <module>
  63. df >> select('one') >> rename(one='first')
  64. File "decorator_test.py", line 31, in __rrshift__
  65. return self.function(other, *self.args, **self.kwargs)
  66. File "decorator_test.py", line 45, in select
  67. return df[cols]
  68. TypeError: 'PipeInto' object has no attribute '__getitem__'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement