Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #INPUT
- #W1 W2 W3 W4
- # 0 1 1 0
- # 1 1 1 1
- # 1 0 0 0
- # 0 1 0 1
- #
- #For every row, randomly select single element that is 1 and make other ones 0
- #Initial zeros stay zeros
- #
- #OUTPUT
- #W1 W2 W3 W4
- # 0 1 0 0
- # 0 1 0 0
- # 1 0 0 0
- # 0 0 0 1
- import pandas as pd
- import numpy as np
- df = pd.DataFrame({'w1': [0, 1, 1, 0],
- 'w2': [1, 1, 0, 1],
- 'w3': [1, 1, 0, 0],
- 'w4': [0, 1, 0, 1]})
- #method 1
- def choose_one(row):
- one = np.random.choice([i for i, v in enumerate(row) if v])
- return [0 if i != one else 1 for i in range(len(row))]
- t, t.columns = df.apply(choose_one, axis=1).apply(pd.Series), df.columns
- #method 2
- idx = pd.DataFrame(np.stack(np.where(df==1))).T.groupby(0).apply(lambda x: x.sample(1)).values
- 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