pandas库学习笔记

#参考网站

https://pandas.pydata.org/pandas-docs/stable/

#加载pandas库
import pandas as pd

#创建表格-pd.DataFrame
#df = pd.DataFrame({行表头1:[列数据1],行表头2:[列数据2]...})
df = pd.DataFrame({
"水果":["苹果","雪梨","香蕉"],
"数量":["11","22","33"],
})

#提取表头对应的数据
df["水果"]

#创建单个列(没表头)-pd.Series 
#Each column in a DataFrame is a Series
fruits = pd.Series(["苹果","雪梨","香蕉"], name="Fruit")
numbers = pd.Series([11, 22, 33], name="Number")

#获取最大值
df["数量"].max()
numbers.max()

#读取CSV文件
csv_file = pd.read_csv("文件名.csv")

#报错:OSError: [Errno 22] Invalid argument: '\u202a
#原因:找文件保存地址的时候,右击属性-->安全-->复制地址(此时复制会在C:\前出现一串 \u202a)

#显示所有列
pd.set_option('display.max_columns', None)
#显示所有行
pd.set_option('display.max_rows', None)
#每行的宽度,避免换行
pd.set_option('display.width', 1000)

#提取前9行数据 head(default = 5)
print(csv_file.head(9))

#提取后9行数据
print(csv_file.tail(9))

#显示各列的数据类型
#integers (int64), floats (float64) and strings (object)
print(csv_file.dtypes)

#转换到excel格式文件
#sheet_name:工作表名称
#index=False:不转换索引
csv_file.to_excel("csv_file.xlsx", sheet_name="passengers", index=False)
#同等于
excel_file = pd.read_excel("csv_file.xlsx", sheet_name="passengers")

#选择多列
multiple_columns = df[["水果", "数量"]]

#筛选大于10的值
above_10 = df[df["数量"] > 10]

#判断某列是否存在某些数据(或)
fruit_select = df[df["水果"].isin(["苹果", "西瓜"])]
#等同于
fruit_select = df[(df["水果"]=="苹果") | (df["水果"]=="西瓜")]

#根据某列筛选非空值
no_na = csv_file[csv_file["xxx"].notna()]

#筛选大于20的水果名称
fruit_names = df.loc[df["数量"] > 20, "水果"]

#选择3到5列对应的10到25行
print(csv_file.iloc[9:25, 2:5])

#第3列0到3行赋值为"xxx"
csv_file.iloc[0:3, 3] = "xxx"

 

posted @ 2021-07-15 23:48  在路上的羊咩  阅读(70)  评论(0)    收藏  举报