本文的起源來自於iThelp中網友的提問:
程式碼是我自已寫的。
import pandas as pd
import numpy as np
df1 = pd.read_excel('實驗設計試解.xlsx', sheet_name = '實驗設計')
df2 = pd.read_excel('實驗設計試解.xlsx', sheet_name = '水準表')
df = pd.DataFrame(np.full((6, 7), np.nan))
df.columns = list(df1.columns)
print('實驗設計組合:')
df1
Out[1]:
In [2]:
print('水準表:')
df2
Out[2]:
In [3]:
print('預期結果:')
df
Out[3]:
In [4]:
print('這種寫法會有語法上的問題:')
for i in df.columns:
for j in df.index:
df[i][j] = df2[i][df1[i][j]]
df
Out[4]:
In [5]:
print('另一種更有效率的寫法:')
df = pd.DataFrame(np.full((6, 7), np.nan))
df.columns = list(df1.columns)
for x in df.columns:
for y in df2.index:
df[x] = np.where(df1[x] == y, df2[x][y], df[x])
df
Out[5]:
In [6]:
print('改良自第一種,修正語法:')
df = df1
for x in df.columns:
for y in df2.index:
df.loc[df[x] == y, x] = df2[x][y]
df
Out[6]: