Home > Net >  python changing value of column with loc doesnt change nothing
python changing value of column with loc doesnt change nothing

Time:03-02

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

CodePudding user response:

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 Trues 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)
  • Related