weixin_53929854
2022-06-30 03:59
采纳率: 100%
浏览 132

python简化for loop

问题遇到的现象和发生背景

我想简化for loop

问题相关代码,请勿粘贴截图

import pandas as pd
import random

df_norms = pd.DataFrame()
df = pd.DataFrame({'Individual_Scale' : ['Scale A','Scale B','Scale C','Scale D','Scale E','Scale F'],
'Score' : [random.random()*100 for _ in range(6)]})

for scale in ['Scale A','Scale B','Scale C','Scale D','Scale E','Scale F']:
df_norms[scale] = sorted([random.random()*100 for _ in range(100)])
df = df.append(pd.Series([scale,random.random()*100], index = df.columns), ignore_index=True)

df_norms = df_norms.T.reset_index()
df_norms = df_norms.round(2)
df_norms

简化下面的for loop
def assesment_function(df,df_norms):
perc = []

for i in range(len(df)):
    for j in range(len(df_norms)):
        if df['Individual_Scale'][i] == df_norms.iloc[j,0]:
            k=1
            while df['Score'][i] >= df_norms.iloc[j,k]:
                if k == 100:
                    break
                else:
                    k += 1
            perc.append(k-1)
df['assesment'] = perc
return df

assesment_function(df,df_norms)

我想要达到的结果

img

6条回答 默认 最新

相关推荐 更多相似问题