wadelin

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内容如下

分类:

技术点:

相关文章: