2021年3月30日 星期二

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

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

python 資料處理

程式碼是我自已寫的。

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]:
abcdefg
00210122
11121010
22002201
30212012
41120201
52001120
In [2]:
print('水準表:')
df2
水準表:
Out[2]:
水準abcdefg
0024132SigmoidSGD640.01
1172364TanhRMSprop1280.05
221446128ReLUAdam2560.10
In [3]:
print('預期結果:')
df
預期結果:
Out[3]:
abcdefg
0NaNNaNNaNNaNNaNNaNNaN
1NaNNaNNaNNaNNaNNaNNaN
2NaNNaNNaNNaNNaNNaNNaN
3NaNNaNNaNNaNNaNNaNNaN
4NaNNaNNaNNaNNaNNaNNaN
5NaNNaNNaNNaNNaNNaNNaN
In [4]:
print('這種寫法會有語法上的問題:')
for i in df.columns:
    for j in df.index:
        df[i][j] = df2[i][df1[i][j]]
df
這種寫法會有語法上的問題:
c:\users\superuser\miniconda3\lib\site-packages\ipykernel_launcher.py:4: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  after removing the cwd from sys.path.
c:\users\superuser\miniconda3\lib\site-packages\pandas\core\indexing.py:205: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  self._setitem_with_indexer(indexer, value)
Out[4]:
abcdefg
024.06.064.0SigmoidRMSprop256.00.10
172.03.0128.0TanhSGD128.00.01
2144.01.032.0ReLUAdam64.00.05
324.06.064.0ReLUSGD128.00.10
472.03.0128.0SigmoidAdam64.00.05
5144.01.032.0TanhRMSprop256.00.01
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]:
abcdefg
024.06.064.0SigmoidRMSprop256.00.10
172.03.0128.0TanhSGD128.00.01
2144.01.032.0ReLUAdam64.00.05
324.06.064.0ReLUSGD128.00.10
472.03.0128.0SigmoidAdam64.00.05
5144.01.032.0TanhRMSprop256.00.01
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]:
abcdefg
024664SigmoidRMSprop2560.10
1723128TanhSGD1280.01
2144332ReLUAdam640.05
324664ReLUSGD1280.10
4723128SigmoidAdam640.05
5144332TanhRMSprop2560.01

【公告】網站遷移,未來內容將發表於新網站!!

 受限於blogger本身架構與限制,本網站所有內容已遷移至新網站,網址如下: https://kuo.us.to/wordpress/