Reputation: 543
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?
Upvotes: 1
Views: 812
Reputation: 13468
You could try this:
count_N = 0
data = {"Brand": [], "N": [], "Percentage": []}
for b in brand:
b = str(b)
data["Brand"].append(b)
for i in columns:
N = len(df.loc[df[i] == b])
count_N = count_N + N
data["N"].append(count_N)
percentage_n = count_N / 351
data["Percentage"].append(percentage_n)
new_df = pd.DataFrame(data)
Upvotes: 1