Consider the following pandas dataframe (df
):
index A B C D E F G weights
1 NaN 1 NaN NaN NaN 3 2 [0.6 , 0.2 , 0.2]
2 3 2 NaN 1 NaN NaN NaN [0.5 , 0.4 , 0.1]
3 NaN NaN 1 2 3 NaN NaN [0.8 , 0.1 , 0.1]
4 NaN 3 1 NaN NaN 2 NaN [0.9 , 0.1 , 0.0]
Desired output (values matched to their corresponding weights at row-level) :
1 NaN 0.6 NaN NaN NaN 0.2 0.2
2 0.1 0.4 NaN 0.5 NaN NaN NaN
3 NaN NaN 0.8 0.1 0.1 NaN NaN
4 NaN 0.0 0.9 NaN NaN 0.1 NaN
My current solution :
def assign_weights(row):
for i in range(1,4):
row.replace(i, row.weights[i-1], inplace=True)
return row
df.apply(assign_weights, axis = 1)
Is there a faster way (for a big dataframe with more weights to be assigned) ?
Not sure if this will be faster, though:
>>> def worker(row):
... n = np.array(row['weights'])
... i = (row.notnull()) & (row.index != 'weights')
... row[i] = n[row[i].astype('int').values - 1]
... return row
>>>
>>> df.apply(worker, axis=1)
A B C D E F G weights
index
1 NaN 0.6 NaN NaN NaN 0.2 0.2 [0.6, 0.2, 0.2]
2 0.1 0.4 NaN 0.5 NaN NaN NaN [0.5, 0.4, 0.1]
3 NaN NaN 0.8 0.1 0.1 NaN NaN [0.8, 0.1, 0.1]
4 NaN 0.0 0.9 NaN NaN 0.1 NaN [0.9, 0.1, 0.0]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments