Issue
I have df that I want to change the column 'b' for all rows when column a is equal to 1, to numbers in the range [0.5,1]. for example:
a b
0 0.2
0 0.4
1 0.02
1 0.001
desire df:
a b
0 0.2
0 0.4
1 0.7
1 0.8
My code is:
df[df['a']==1].reset_index(drop=True).loc[0:len(df[df['a']==1]), 'b'] = np.linspace(0.5,0.99,len (df[df['a']==1]))
But nothing changed. Thx
Solution
For modify column in original ataFrame use DataFrame.loc
, for count True
values use sum
:
m = df['a']==1
df.loc[m, 'b'] = np.linspace(0.5,0.99, m.sum())
print (df)
a b
0 0 0.20
1 0 0.40
2 1 0.50
3 1 0.99
EDIT: For match first N
values: (N
is less like number of True
s in mask m
):
N = 3
m = (df['a']==1)
m1 = m[m].head(N).reindex(df.index, fill_value=False)
df.loc[m1, 'b'] = np.linspace(0.5,0.99, N)
Answered By - jezrael
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.