2017-10-11 103 views
-2

Python新手!我對製表測驗分數簡單的數據幀:循環停止在預定的意思

df = pd.DataFrame({'Sam':[20,20,20,20,20], 'Jim': [20,20,20,20,15], 
'Stacy': [20,20,20,20,30], 'Leslie': [20,20,20,20,20], 'Jonathan': 
[20,20,20,20,15]}) 

現在,我想寫的東西,改變每一列的頂部值(從0開始),直到它的相應平均值等於什麼預定,然後移動到下一列。很容易添加一個新行,並手動完成,直到獲得我想要的結果(如下所示)。但是,我正在尋找一些能夠讓程序在iloc字段中進行迭代的操作,以便獲得預定義的'mean2'值。我想這會需要一些while循環,但無法弄清楚語法。代碼下方最終所需結果的屏幕截圖。謝謝!

df.loc['mean1'] = df.mean() 
df.iloc[0:1,0:5] = 17, 17, 22, 22, 22 
df.loc['mean2'] = df.iloc[:5,:].mean() 
df 

期望的最終數據幀的屏幕截圖。

回答

0

糾正我,如果我錯了,但如果我重新制定你的問題:
你想要的是找到每個particiant(列)的第一次測驗分數的值(df.loc [0]),將確保參與者有一個平均目標得分(mean2)?

如果它是你可以做一些類似的情況:

# a function that estimate the quiz value to have for obtaining mean score target 
def estimate_replace(quiz_id, mean_target, participant_series): 
    data = participant_series.loc[participant_series.index != quiz_id].values 
    participant_series['mean1'] = participant_series.mean() 
    participant_series['mean2'] = mean_target 

    # Here is the key function! 
    participant_series.loc[quiz_id] = mean_target*(len(data)+1) - data.sum() 
    return participant_series 

#mean2 : mean scores target per participant 
mean_score_target = {'Jim':18.4, 
        'Jonathan':18.4, 
        'Leslie':20.4, 
        'Sam':20.4, 
        'Stacy':22.4} 

#the quiz id to replace, 0 in your case 
quiz_id = 0 

df = df.apply(lambda x: estimate_replace(quiz_id,mean_score_target[x.name],x)) 

注意,該代碼可以使用任意數量的測驗值(行)和運作的,你可以指定競猜值來估算/替換(quiz_id )。

你會然後得到以下的輸出:

 Jim  Jonathan Leslie Sam Stacy 
0  17.0  17.0 22.0 22.0 22.0 
1  20.0  20.0 20.0 20.0 20.0 
2  20.0  20.0 20.0 20.0 20.0 
3  20.0  20.0 20.0 20.0 20.0 
4  15.0  15.0 20.0 20.0 30.0 
mean1 19.0  19.0 20.0 20.0 22.0 
mean2 18.4  18.4 20.4 20.4 22.4 
+0

歡迎你! –