https://www.bilibili.com/video/BV1D5411a7tn
# Section0
print("-"*30 + "Begin Section 0 開場" + "-"*30)
print("lesson7 數據選擇")
print("1.列選擇\n2.行選擇\n3.行列選擇")
print("-"*30 + "End Section 0 開場" + "-"*30)
import pandas as pd
# Section1 列
df = pd.read_excel(r"D:/Users/sf_xiaowei_lin/PycharmProjects/pythonProject/venv/Lesson7.xlsx")
#定義行標
df.index = ["one","two","three","four","five"]
print("readload content of table :")
print(df,'\n')
# 只選擇名稱列
print("只選擇名稱列:")
print(df["名稱"],'\n')
# 選擇名稱列和觀看次數
print("選擇名稱列和觀看次數:")
print(df[["名稱","觀看次數"]],'\n')
#選擇指定列,:冒號表示所有行,后面表示第幾列
print("選擇指定列:")
print(df.iloc[:,[0,2]],'\n')
#選擇連續的列
print("選擇第一列到第四列(不包括第四列):")
print(df.iloc[:,0:3],'\n')
# Section2 select row
# select only first row
print("select only first row :")
print(df.loc["one"],'\n')
# select first row and third row
print("select first row and third row :")
print(df.loc[["one","three"]],'\n')
# 通過第幾行來選擇
print("通過第幾行來選擇 :")
print(df.iloc[0],'\n')
# 通過行數選擇第一行和第三行
print("通過行數選擇第一行和第三行 :")
print(df.iloc[[0,2]],'\n')
# 選擇連續的行
print("選擇連續的行 :")
print(df.iloc[0:3],'\n')
# 選擇滿足條件的數據
# 記得多條件要加括號
print("選擇觀看數超過200&評論數超過20的數據 :")
print(df[(df["觀看次數"] > 200) & (df["評論數"] > 20)],'\n')
# Section 3 : select row and colum at same time
# loc傳入行/列索引名稱,iloc行/列數
print("行列都用索引名稱 :")
print(df.loc[["one","three"],["名稱","觀看次數"]],'\n')
print("行和列都是索引數 :")
print(df.iloc[[0,2],[0,1]],'\n')
print("行列中有切片索引 :")
print(df.iloc[0:3,[0,1]],'\n')
# 根據條件來選擇行列
print("根據條件來選擇行列 :")
print(df[df['觀看次數'] > 240][['名稱','觀看次數']],'\n')
Lesson7.xlsx內容如下