'Save output dynamically in a for loop in another dataframe (pandas)
I have 2 lists
brand = ["Old Wild West","Rosso Pomodoro","Panino Giusto"]
columns = ["Top1", "Unaided1", "Unaided2", "Unaided3", "Unaided4"]
And a dataframe:
df=
brand | Top1 | Unaided1 | Unaided2 | Unaided3 | Unaided4
Old Wild West | 1 | 0 | 0 | 0 | 0
Rosso Pomodoro | 1 | 0 | 0 | 0 | 0
Panino Giusto | 0 | 1 | 0 | 0 | 0
I'm iterating with a for loop:
count_N= 0
for b in brand:
b=str(b)
print(b)
for i in columns:
N=len(df.loc[df[i]==b])
count_N=count_N+N
print(count_N)
percentage_n=count_N/351
print(percentage_n)
print(" ")
this prints outputs like this (numbers are random):
Old Wild West
30
0.08547008547008547
Rosso Pomodoro
55
0.15669515669515668
Panino Giusto
123
0.3504273504273504
I woud like to save this output in another dataframe. The desired output is (numbers are random):
df2=
Brand | N | Percentage
Old Wild West | 30 | 0.1
Rosso Pomodoro | 55 | 0.001
Panino Giusto | 123 | 0.2
Could you help me?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
