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

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

python資料處理請教

程式碼是我自已寫的。

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]:
df_temp = df.copy()
df_temp['GOAT_sub'] = df_temp['GOAT'].str.split('/').tolist()
df_temp['TYPE_sub'] = df_temp['TYPE'].str.split('/').tolist()

df_temp
Out[2]:
GROUP GOAT TYPE TIME GOAT_sub TYPE_sub
0 R 15/10 A/B 2 [15, 10] [A, B]
1 W 10/7/11 A/B/B 3 [10, 7, 11] [A, B, B]
2 W 9 A 2 [9] [A]
3 R 12 B 2 [12] [B]
4 R 8/13 B/A 3 [8, 13] [B, A]
5 W 10 B 2 [10] [B]
In [5]:
# 設定solution來存最後結果
solution = []
for i in range(len(df_temp)):
    #設定temp_RESULT來存暫時的結果
    temp_RESULT = []
    for j in range(len(df_temp['TYPE_sub'][i])):
        if ((df_temp['GROUP'][i] == 'R') & (df_temp['TYPE_sub'][i][j] == 'A')):
            df_temp['temp'+str(j)] = int(df_temp['GOAT_sub'][i][j])*df_temp['TIME'][i]*0.3
        elif ((df_temp['GROUP'][i] == 'R') & (df_temp['TYPE_sub'][i][j] == 'B')):
            df_temp['temp'+str(j)] = int(df_temp['GOAT_sub'][i][j])*df_temp['TIME'][i]*0.5
        elif ((df_temp['GROUP'][i] == 'W') & (df_temp['TYPE_sub'][i][j] == 'A')):
            df_temp['temp'+str(j)] = int(df_temp['GOAT_sub'][i][j])*df_temp['TIME'][i]*0.4
        elif ((df_temp['GROUP'][i] == 'W') & (df_temp['TYPE_sub'][i][j] == 'B')):
            df_temp['temp'+str(j)] = int(df_temp['GOAT_sub'][i][j])*df_temp['TIME'][i]*0.3
        L = str(df_temp['temp'+str(j)][0])
        temp_RESULT.append(L)
    temp_RESULT = '/'.join(temp_RESULT)
    solution.append(temp_RESULT)

    print(temp_RESULT)

solution
9.0/10.0
12.0/6.3/9.9
7.2
12.0
12.0/11.7
6.0
Out[5]:
['9.0/10.0', '12.0/6.3/9.9', '7.2', '12.0', '12.0/11.7', '6.0']
In [6]:
df['RESULT'] = solution
df
Out[6]:
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 [ ]:

發佈留言

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