Home > Software design >  using pandas Creating a new column after every For loop iteration in Python
using pandas Creating a new column after every For loop iteration in Python

Time:09-18

Input is like below csv file

    y   proba
1   1    12
2   1    65
3   1    1
4   1    54


for i in range(len(df1["proba"])):
  a=pd.concat([df1, pd.Series(df1["proba"] >= df1["proba"][i], name=f'tau{i}').astype(int)], axis=1)
  print(a)

I apply this but wont get answer correctly

Need a answer like below

   y  proba   tau1    tau2    tau3    tau4    
1   1   12      1       0       1       0       
2   1   65      1       1       1       1       
3   1   1       0       0       1       0       
4   1   54      1       0       1       1 

CodePudding user response:

Try:

for i, v in enumerate(df["proba"]):
    df[f"tau{i 1}"] = (df["proba"] >= v).astype(int)

print(df)

Prints:

   y  proba  tau1  tau2  tau3  tau4
1  1     12     1     0     1     0
2  1     65     1     1     1     1
3  1      1     0     0     1     0
4  1     54     1     0     1     1

CodePudding user response:

new = df1.copy()
for i in range(len(df1["proba"])):
  a=pd.DataFrame(pd.Series(df1["proba"] >= df1["proba"][i], name=f'tau{i}').astype(int))
  new.insert(len(new.columns), f'tau{i}', a.values)
  • Related