---
# System prepended metadata

title: 第九週筆記

---

# 第九週筆記
## 讀寫雲端文字檔:

### 寫入CSV:
```
with open('/content/drive/MyDrive/___DataSet//001_Hello.txt', 'w') as f:
  f.write('Hello Google Drive 趙梓豐')
```

### 讀取CSV:
```
with open('/content/drive/MyDrive/___DataSet//001_Hello.txt', 'r') as f:  
  ss=f.read()
  print(ss)
```
結果:
```
Hello Google Drive 趙梓豐
```

### 刪除檔案:
```
import os
if os.path.exists("/content/drive/MyDrive/___DataSet//001_Hello.txt"):
  os.remove("/content/drive/MyDrive/___DataSet//001_Hello.txt")
  print("檔案已經刪除")
else:
  print("檔案不存在")
```
結果:
```
檔案已經刪除
```

## 處理外部檔案:

### 讀取excel檔:

1.
```
import pandas as pd
df = pd.read_excel('/content/drive/My Drive/___DataSet/001_Income_F.xlsx')
df
```
結果:
![](https://i.imgur.com/vIfAfLF.png)

2.
```
import pandas as pd
data = pd.read_excel("/content/drive/My Drive/___DataSet/110 學年度全國大專校院及校長名錄(含學校本部地址).xlsx")
data
```
結果:
![](https://i.imgur.com/xSAJunY.png)

3.
```
import pandas as pd
df = pd.read_excel('/content/drive/My Drive/___DataSet/身高體重.xlsx')
df
```
結果:
![](https://i.imgur.com/JmjWePi.png)


### 讀取CSV檔:
```
df = pd.read_csv("/content/drive/My Drive/___DataSet/opendata110road.csv")
df
```
結果:
![](https://i.imgur.com/ElA5tA8.png)

## Pandas DataFrame:

### 表格如何建立:

1.
```
import pandas as pd
grades = {
    "name": ["Mike", "Sherry", "Cindy", "John"],
    "math": [80, 75, 93, 86],
    "chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
df
```
結果:
![](https://i.imgur.com/cd0s1Lr.png)

2.
```
import pandas as pd
grades = {
    "學號": ["A001", "A002", "A003", "A004", "A005"],
    "體重": [60, 50, 80, 75, 72],
    "身高": [165, 157, 182, 175, 170]
}
df = pd.DataFrame(grades)
 
print("使用字典來建立df：")
df
```
結果:
![](https://i.imgur.com/SYpgm94.png)

## 取得表格資料:

### head() and tail():
```
grades = [
    ["Mike", 80, 63],
    ["Sherry", 75, 90],
    ["Cindy", 93, 85],
    ["John", 86, 70]
]
df = pd.DataFrame(grades)
df.columns = ["student_name", "math_score", "chinese_score"]
df.columns = ["name", "math", "chinese"]
print(df.head(1))
print(df.tail(1))
```
結果:
```
 name  math  chinese
0  Mike    80       63
   name  math  chinese
3  John    86       70
```

### 中括號[]:
```
import pandas as pd
grades = {
    "學號": ["A001", "A002", "A003", "A004", "A005"],
    "體重": [60, 50, 80, 75, 72],
    "身高": [165, 157, 182, 175, 170]
}
df = pd.DataFrame(grades)
print(df["身高"])
print(df[["身高","體重"]])
print(df[0:3])
```
結果:
```
0    165
1    157
2    182
3    175
4    170
Name: 身高, dtype: int64
    身高  體重
0  165  60
1  157  50
2  182  80
3  175  75
4  170  72
     學號  體重   身高
0  A001  60  165
1  A002  50  157
2  A003  80  182
```

### at[資料索引值,欄位名稱]:
```
print("利用at()方法取得索引值為1的math欄位資料")
print(df.at[1, "身高"])
```
結果:
```
利用at()方法取得索引值為1的math欄位資料
157
```

### iat[資料索引值,欄位順序]
```
print("利用iat()方法取得索引值為1的第一個欄位資料")
print(df.iat[4,2])
```
結果:
```
利用iat()方法取得索引值為1的第一個欄位資料
170
```

### loc[資料索引值,欄位名稱]:
```
print("取得資料索引值為1和3的name及chinese欄位資料集")
print(df.loc[[1, 3], ["學號", "體重"]])
new_df=df.loc[[1, 3], ["學號", "體重"]]
type(new_df)
```
結果:
```
取得資料索引值為1和3的name及chinese欄位資料集
     學號  體重
1  A002  50
3  A004  75
pandas.core.frame.DataFrame
```

### iloc[資料索引值,欄位順序]:
```
print("取得資料索引值為1和3的第一個及第三個欄位資料集")
print(df.iloc[[1, 3], [0, 2]])
```
結果:
```
取得資料索引值為1和3的第一個及第三個欄位資料集
     學號   身高
1  A002  157
3  A004  175
```

## range使用介紹:

### 練習:
```
for i in range(0,5):
  print(i)
  print(df.at[i, "學號"])
```
結果:
```
0
A001
1
A002
2
A003
3
A004
4
A005
```

### 雙迴圈:
```
for i in range(0,5):
  for j in range(0,5):
    print(f'{i},{j}')
```
結果:
```
0,0
0,1
0,2
0,3
0,4
1,0
1,1
1,2
1,3
1,4
2,0
2,1
2,2
2,3
2,4
3,0
3,1
3,2
3,3
3,4
4,0
4,1
4,2
4,3
4,4
```

## 回家作業:

1.
```
import pandas as pd
grades = {
    "學號": ["A001", "A002", "A003", "A004", "A005"],
    "體重": [60, 50, 80, 75, 72],
    "身高": [165, 157, 182, 175, 170]
}
df = pd.DataFrame(grades)
print(df.iloc[[0], [0,1,2]])
```
結果:
```
學號  體重   身高
0  A001  60  165
```

2.
```
import pandas as pd
grades = {
    "學號": ["A001", "A002", "A003", "A004", "A005"],
    "體重": [60, 50, 80, 75, 72],
    "身高": [165, 157, 182, 175, 170]
}
df = pd.DataFrame(grades)
for i in range(0,5):
  for j in range(i,i+1):
    for k in range(i,i+1):
      print(f'{df.at[i, "學號"]},{df.at[j, "體重"]},{df.at[k, "身高"]}')
```
結果:
```
A001,60,165
A002,50,157
A003,80,182
A004,75,175
A005,72,170
```