Python學習筆記:實驗設計組合(二)_另解

 本文的起源來自於iThelp中網友的提問:

python資料處理請教

程式碼是我自已寫的。

110/12/13 另一種寫法:

import pandas as pd
import numpy as np

df = pd.DataFrame(
    {
      'GROUP':   ['R','W','W','R','R','W'],
      'GOAT':    ['15/10','10/7/11','9','12','8/13','10'],
      'TYPE':    ['A/B','A/B/B','A','B','B/A','B'],
      'TIME': [2,3,2,2,3,2]
    }
)

df
Out[1]:
GROUP GOAT TYPE TIME
0 R 15/10 A/B 2
1 W 10/7/11 A/B/B 3
2 W 9 A 2
3 R 12 B 2
4 R 8/13 B/A 3
5 W 10 B 2
In [2]:
go = df['GOAT'].str.split('/')
ty = df['TYPE'].str.split('/')
co = range(len(df))
result = []
for a, b, c in zip(go, ty, co):
    re = []
    for i in range(len(b)):
        gr = df['GROUP'][c]
        ti = df['TIME'][c]
        if ((gr == 'R') & (b[i] == 'A')):
            r = int(a[i])*int(ti)*0.3
        elif ((gr == 'R') & (b[i] == 'B')):
            r = int(a[i])*int(ti)*0.5
        elif ((gr == 'W') & (b[i] == 'A')):
            r = int(a[i])*int(ti)*0.4
        elif ((gr == 'W') & (b[i] == 'B')):
            r = int(a[i])*int(ti)*0.3

        li = str(r)
        re.append(li)
        #print(a[i], b[i], gr, ti, r)
    #print('/'.join(re))
    result.append('/'.join(re))
    
df['RESULT'] = result
df
Out[2]:
GROUP GOAT TYPE TIME RESULT
0 R 15/10 A/B 2 9.0/10.0
1 W 10/7/11 A/B/B 3 12.0/6.3/9.9
2 W 9 A 2 7.2
3 R 12 B 2 12.0
4 R 8/13 B/A 3 12.0/11.7
5 W 10 B 2 6.0
In [ ]:

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *