Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. #INPUT
  2. #W1 W2 W3 W4
  3. # 0 1 1 0
  4. # 1 1 1 1
  5. # 1 0 0 0
  6. # 0 1 0 1
  7. #
  8. #For every row, randomly select single element that is 1 and make other ones 0
  9. #Initial zeros stay zeros
  10. #
  11. #OUTPUT
  12. #W1 W2 W3 W4
  13. # 0 1 0 0
  14. # 0 1 0 0
  15. # 1 0 0 0
  16. # 0 0 0 1
  17.  
  18. import pandas as pd
  19. import numpy as np
  20.  
  21.  
  22. df = pd.DataFrame({'w1': [0, 1, 1, 0],
  23. 'w2': [1, 1, 0, 1],
  24. 'w3': [1, 1, 0, 0],
  25. 'w4': [0, 1, 0, 1]})
  26.  
  27. #method 1
  28. def choose_one(row):
  29. one = np.random.choice([i for i, v in enumerate(row) if v])
  30. return [0 if i != one else 1 for i in range(len(row))]
  31.  
  32. t, t.columns = df.apply(choose_one, axis=1).apply(pd.Series), df.columns
  33.  
  34. #method 2
  35. idx = pd.DataFrame(np.stack(np.where(df==1))).T.groupby(0).apply(lambda x: x.sample(1)).values
  36. t, t.values[idx[:, 0], idx[:, 1]] = pd.DataFrame(np.zeros(df.shape, dtype=np.int), columns=df.columns), 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement