Home > Enterprise >  Creating a new column after every For loop iteration in Python
Creating a new column after every For loop iteration in Python

Time:09-17

Create a New Column after every for loop iteration

proba=[12,65,1,54]
tau=[]

for i in range(len(proba)):
  for j in range(len(proba)):
    if proba[j]>=proba[i]:
      tau.append(1)
    else:
      tau.append(0)
print(tau)

Getting output like this as below:

[1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1]

But I required output like below:

proba    tau1    tau2    tau3    tau4    
12        1       0       1       0       
65        1       1       1       1       
1         0       0       1       0       
54        1       0       1       1  

we can use pandas and numpy also to make code more generic

CodePudding user response:

You could use a combination of pandas and numpy:

proba = np.array([12,65,1,54])
df = pd.DataFrame(proba, columns=['proba'])
for i in range(len(proba)):
    df = pd.concat([df, pd.Series(proba >= proba[i], name=f'tau{i}').astype(int)], axis=1)

Output:

   proba  tau0  tau1  tau2  tau3
0     12     1     0     1     0
1     65     1     1     1     1
2      1     0     0     1     0
3     54     1     0     1     1

CodePudding user response:

Builtin data structures such as dictionaries and/or lists, serve well for creating dataframes

import pandas as pd

proba = [12, 65, 1, 54]
taus = {}
for idx, i in enumerate(proba):
    vals=[]
    for j in proba:
        if j >= i:
            vals.append(1)
        else:
            vals.append(0)
    taus[f"tau{idx}"] = vals

df = pd.DataFrame(taus)
df["proba"] = proba
  • Related