I have dataframe in the following form:
W1 W2 W3 W4 0 1 1 0 1 1 1 1 1 0 0 0 0 1 0 1
For every row, I want to randomly select single element that is 1 and make other ones zero. Initial zeros stay zeros Eg
W1 W2 W3 W4 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 1
I have very convoluted solution that uses iterrows()
, but I'm looking for a pandastic one.
Idea is extract positions, shuffling and then remove duplicates by first column 0
- by rows:
#get positions of 1
a = np.where(df == 1)
#create nd array
X = np.hstack((a[0][:, None], a[1][:, None]))
#shuffling
np.random.shuffle(X)
#remove duplicates
vals = pd.DataFrame(X).drop_duplicates(0).values
#set 1
arr = np.zeros(df.shape)
arr[vals[:,0],vals[:,1]] = 1
df = pd.DataFrame(arr.astype(int), columns=df.columns, index=df.index)
print (df)
W1 W2 W3 W4
0 0 0 1 0
1 0 0 0 1
2 1 0 0 0
3 0 1 0 0
IIUC, you want to randomly select 1 from every row and make the rest 0. Here's one approach. Sample the indices and based on indices assign 1. ie
idx = pd.DataFrame(np.stack(np.where(df==1))).T.groupby(0).apply(lambda x: x.sample(1)).values
# array([[0, 2],
# [1, 1],
# [2, 0],
# [3, 3]])
ndf = pd.DataFrame(np.zeros(df.shape),columns=df.columns)
ndf.values[idx[:,0],idx[:,1]] = 1
W1 W2 W3 W4
0 0 0 1 0
1 1 0 0 0
2 1 0 0 0
3 0 1 0 0
Here is mixture of functional and pandastic approach:
df = pd.DataFrame({'w1': [0, 1,1,0],
'w2': [1, 1,0,1],
'w3': [1, 1,0,0],
'w4': [0, 1,0,1]})
df
w1 w2 w3 w4
0 0 1 1 0
1 1 1 1 1
2 1 0 0 0
3 0 1 0 1
def choose_one(row):
"""
returns array with randomly chosen positive value and 0 otherwise
"""
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))]
apply for each row
df.apply(choose_one, 1)
w1 w2 w3 w4
0 0 1 0 0
1 0 1 0 0
2 1 0 0 0
3 0 0 0 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.