python3之pandas库

发布时间 2024-01-03 15:58:29作者: carol2014
pandas中有两类非常重要的数据结构,即序列Series和数据框DataFrame。
Series类似于numpy中的一维数组;DataFrame类似于numpy中的二维数组。

DataFrame创建

# 通过二维数组创建数据框
df1 = pd.DataFrame(np.arange(12).reshape(4, 3))
print(df1)
# 通过字典的方式创建数据框
dic2 = {
    "a": [1, 2, 3, 4],
    "b": [5, 6, 7, 8],
    "c": [9, 10, 11, 12],
    "d": [13, 14, 15, 16],
}
dic3 = {
    "one": {"a": 1, "b": 2, "c": 3, "d": 4},
    "two": {"a": 5, "b": 6, "c": 7, "d": 8},
    "three": {"a": 9, "b": 10, "c": 11, "d": 12},
}
df2 = pd.DataFrame(dic2)
df3 = pd.DataFrame(dic3)
print(df2, df3)
# 通过数据框的方式创建数据框
df4 = df3[["one", "three"]]
print(df4)

 Series创建 

# 通过一维数组创建序列
s1 = pd.Series(np.arange(5))
print(s1)
# 通过字典的方式创建序列
s2 = pd.Series({"a": 1, "b": 2})
print(s2)
# 通过DataFrame中的某一行或某一列创建序列
s3 = df3["one"]
print(s3)
s1.index = ["a", "b", "c", "d", "e"]
print(s1[4])
print(s1["a"])
print(s1[[1, 3]])
print(s1[:4])
print(s1["c":])

文件

# 读取远端csv文件
data_url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv"
df = pd.read_csv(data_url)

# 读取本地csv文件
df = pd.read_csv("../../seaborn-data-master/tips.csv")

mysql_cn = pymysql.connect(
    host="127.0.0.1",
    user="root",
    password="",
    port=3306,
    database="test",
    charset="utf8",
)
# 读取Mysql数据
df = pd.read_sql("select * from blog_note;", con=mysql_cn)
mysql_cn.close()
# 数据导出到csv文件
df.to_csv("../../gen-files/note.csv", encoding="utf-8", index=True)

# excel文件
df = pd.read_excel("../../source-files/info.xls")

数据

# 打印全部数据
print(df)
# 打印维度
print(df.shape)
# 打印数据前5行、后5行
print(df.head(), df.tail())
# 打印数据前2行、后2行
print(df.head(2), df.tail(2))
# 打印列名、行名
print(df.columns, df.index)
# 选取第3行
print(df.iloc[3])
# 选取第2到第3行
print(df.iloc[2:4])
# 提取不连续行和列的数据
print(df.iloc[[1, 3, 5], [2, 4]])
# 选取第0行1列的元素
print(df.iloc[0, 1])
# 专门提取某一个数据
print(df.iat[3, 2])
# 筛选出需要的数据
print(df[df.tip > 8])
print(df[(df.tip > 7) | (df.total_bill > 50)])
print(df[(df.tip > 7) & (df.total_bill > 50)])
print(df[["day", "time"]][(df.tip > 7) | (df.total_bill > 50)])

# 数据转置
print(df.T)
# 按tip列升序排序
print(df.sort_values(by="tip"))
# 填充缺失值
print(df.fillna(1))
# 用前一个数据代替缺失值
print(df.fillna(method="pad"))
# 用后一个数据代替缺失值
print(df.fillna(method="bfill"))
# 删除缺失行
print(df.dropna(axis=0))
# 删除缺失列
print(df.dropna(axis=1))
# 插值法填补缺失值
print(df.interpolate())

# 数据分组
group = df.groupby("day")
print(df)
# 每一组的第一行数据
print(group.first())
# 每一组的最后一行数据
print(group.last())

# 非空元素计算
print(df.count())
# 计数统计
print(df["sex"].value_counts())
# 最小值
print(df.min(numeric_only=True))
# 最大值
print(df.max(numeric_only=True))
s1 = df["tip"]
# 最大值的位置
print(s1.idxmax())
# 最小值的位置
print(s1.idxmin())
# 10%分位数
print(df.quantile(0.1, numeric_only=True))
# 求和
print(df.sum(numeric_only=True))
# 均值
print(df.mean(numeric_only=True))
# 中位数
print(df.median(numeric_only=True))
# 众数
print(df.mode(numeric_only=True))
# 方差
print(df.var(numeric_only=True))
# 标准差
print(df.std(numeric_only=True))
# 偏度
print(df.skew(numeric_only=True))
# 峰度
print(df.kurt(numeric_only=True))
# 描述性统计
print(df.describe())
# 相关系数
print(df.corr(numeric_only=True))
# 某一个变量与其余变量的相关系数
print(df.corrwith(df["size"], numeric_only=True))
# 协方差矩阵
print(df.cov(numeric_only=True))

时间日期

# 时间日期
print(pd.to_datetime(["02-03-2023", "2023-JAN-10"]))
print(pd.date_range("2023-11-01", "2023-11-03"))
sr = pd.Series(np.arange(100), index=pd.date_range("2023-01-01", periods=100))
print(sr["2023-03"])
print(sr["2023-03-01":"2023-03-05"])
print(sr.resample("W").sum())