pandas使用介绍

2025-11-07 20:56:00
admin
原创 276
摘要:pandas使用介绍

一、pandas使用介绍

1、代码仓库:https://github.com/pandas-dev/pandas

2、安装介绍:https://pandas.pydata.org/docs/getting_started/install.html

3、使用介绍:https://pandas.pydata.org/docs/getting_started/intro_tutorials/index.html

4、函数列表:https://pandas.pydata.org/docs/reference/series.html

5、函数列表:https://pandas.pydata.org/docs/reference/frame.html

6、pandas数据结构:二维数据结构DataFrame不可以修改行数,可以在任意位置插入列

7、pandas数据结构一维数据结构Series,不可以修改长度;

8、pandas安装命令:pip install "pandas[excel]"


读写函数:

1、pb.read_csv(filename),读取csv文件;

2、pd.read_json(path_or_buf),读取json文件;

3、pd.read_excel(filename, sheet_name),读取excel文件;

4、DataFrame.to_csv(filename, index=False),写入csv文件;

5、DataFrame.to_json(path_or_buf, orient, indent),写入json文件

6、DataFrame.to_excel(filename, sheet_name, index=False),写入excel文件;


创建DataFrame:

df = pd.DataFrame({
        "Name": [ "Braund", "Allen", "Bonnell"],
        "Age": [22, 35, 58],
        "Sex": ["male", "male", "female"],
    })
print(df.info())

print(df.index)

print(df.columns)
print(df)


创建Series:

ages = pd.Series([22, 35, 58], name="Age")

print(ages.info())
print(ages.index)
print(ages)


二、pandas使用详解

查询数据:

1、container.head(n),获取前n行数据;

2、container.tail(n),获取后n行数据;

3、container[],基于列标签查询,基于行整数切片查询,允许布尔数组;

4、container.loc[],基于标签查询,允许单个标签,允许标签数组,允许布尔数组;

5、container.iloc[],基于整数位置查询,允许单个整数,允许整数切片,允许布尔数组;


统计函数:

1、container.idxmax(),最大值的标签;

2、container.idxmin(),最小值的标签;

3、container.max(),计算最大值;

4、container.min(),计算最小值;

5、container.agg(),多种聚合操作;

6、container.describe(),生成统计信息;

7、container.groupby(),数据进行分组;

8、container.value_counts(),唯一数据数量;


数据转换:

1、DataFrame.replace:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html

2、DataFrame.apply:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html

3、DataFrame.rename:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rename.html

4、DataFrame.sort_values:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.sort_values.html

5、DataFrame.pivothttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html

6、DataFrame.pivot_table:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot_table.html

7、DataFrame.reset_index:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reset_index.html

8、DataFrame.melthttps://pandas.pydata.org/docs/reference/api/pandas.melt.html


数据转换:

1、DataFrame.replace(to_replace, value),替换指定元素的值;

2、DataFrame.apply(func, axis=0),对每列数据进行处理,生成新的行;

3、DataFrame.apply(func, axis=1),对每行数据进行处理,生成新的列;

4、DataFrame.rename(index, columns, inplace),重命名行标签或列标签;

5、DataFrame.sort_values(by, axis, ascending, inplace),行排序或列排序;

6、DataFrame.pivot(columns, index, values),长表转换为宽表,不能使用聚合函数;

7、DataFrame.pivot_table(columns, index, values, aggfunc),长表转换为宽表,可以使用聚合函数;

8、DataFrame.reset_index(level, inplace),清除原始的行索引,增加默认的整数索引;

9、DataFrame.melt(id_vars, var_name, value_name),宽表转换为长表;


多表操作:

1、pandas.concat:https://pandas.pydata.org/docs/reference/api/pandas.concat.html

2、pandas.merge:https://pandas.pydata.org/docs/reference/api/pandas.merge.html

3、pandas.concat(objs, join, keys),合并两个表格,纵向合并或横向合并,默认纵向合并;

4、pandas.merge(left, right, how, on),连接两个表格,需要指定连接方式和连接条件;


三、pandas其他操作

1、pandas.date_range(start, periods, freq),生成时间序列,可选时间频率;

2、pandas.to_datetime(arg, format),转换入参为时间对象,可选时间格式;

3、container.resample(rule),转换时间序列的时间频率,必须使用聚合函数;

4、时间序列存在dt访问器,便于操作时间序列;

5、序列存在str访问器:inferred_dtype in ["string", "empty", "bytes", "mixed", "mixed-integer"]

6、序列存在str访问器:mixed表示这一列都是对象,mixed-integer表示这一列至少存在一个数字;


四、pandas绘制图表

绘制图表:绘制折线图,展示每列数据的趋势

import matplotlib.pyplot as plt

df.plot(marker="o", figsize=(10, 6), title="Weather Data")
plt.xlabel("Date")
plt.ylabel("Value")
plt.grid(True)
plt.tight_layout()
plt.show()


绘制图表:绘制面积图,展示每列数据的贡献

import matplotlib.pyplot as plt

df.plot.area(figsize=(12, 4), subplots=True)
plt.grid(True)
plt.tight_layout()
plt.show()


绘制图表:绘制箱线图,展示每列数据的分布

import matplotlib.pyplot as plt

df.plot.box(figsize=(8, 6))
plt.grid(True)
plt.tight_layout()
plt.show()


绘制图表:绘制散点图,展示两个指标的关系

import matplotlib.pyplot as plt

df.plot.scatter(
    x="Temperature", y="Humidity",
    alpha=0.5, s=10, figsize=(8, 6),
    title="Temperature vs Humidity",
)
plt.xlabel("Temperature (°C)")
plt.ylabel("Humidity (%)")
plt.grid(True)
plt.tight_layout()
plt.show()


绘制图表:绘制面积图,然后保存图片为文件

import matplotlib.pyplot as plt

fig, axs = plt.subplots(nrows=3, ncols=1, sharex=True, figsize=(12, 4))
df.plot.area(ax=axs, subplots=True)
plt.grid(True)
plt.tight_layout()
fig.savefig("output.png")
plt.show()

发表评论
评论通过审核之后才会显示。