将输出动态保存在另一个数据帧(panda)的for循环中



我有两个列表

brand = ["Old Wild West","Rosso Pomodoro","Panino Giusto"]
columns = ["Top1", "Unaided1", "Unaided2", "Unaided3", "Unaided4"]

和一个数据帧:

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 

我正在使用for循环进行迭代:

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(" ")

这样打印输出(数字是随机的(:

Old Wild West
30
0.08547008547008547

Rosso Pomodoro
55
0.15669515669515668

Panino Giusto
123
0.3504273504273504

我想把这个输出保存在另一个数据帧中。所需输出为(数字是随机的(:

df2=

Brand          | N   | Percentage
Old Wild West  | 30  | 0.1
Rosso Pomodoro | 55  | 0.001
Panino Giusto  | 123 | 0.2

你能帮我吗?

你可以试试这个:

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)

最新更新