Pandas的DataFrame的生产,DF数据查看

本文介绍了Pandas在Python中的基本使用,包括导入库、创建Series和DataFrame对象,以及数据查看和操作。Pandas提供了方便的数据分析功能,如DataFrame的列具有不同的数据类型,并支持与NumPy的集成。文章还提到了数据加载、清洗、统计计算以及数据可视化的可能性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这篇文档介绍了 Pandas 的入门使用方法。Pandas 是 Python 的一个数据分析库,可以方便地操作数据和进行数据分析。

本节以下列方式导入 Pandas 与 NumPy:

In [1]: import numpy as np

In [2]: import pandas as pd

#生成对象

用值列表生成 Seriesopen in new window 时,Pandas 默认自动生成整数索引:

In [3]: s = pd.Series([1, 3, 5, np.nan, 6, 8])

In [4]: s
Out[4]:
0    1.0
1    3.0
2    5.0
3    NaN
4    6.0
5    8.0
dtype: float64

用含日期时间索引与标签的 NumPy 数组生成 DataFrameopen in new window

In [5]: dates = pd.date_range('20130101', periods=6)

In [6]: dates
Out[6]:
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
               '2013-01-05', '2013-01-06'],
              dtype='datetime64[ns]', freq='D')

In [7]: df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))

In [8]: df
Out[8]:
                   A         B         C         D
2013-01-01  0.469112 -0.282863 -1.509059 -1.135632
2013-01-02  1.212112 -0.173215  0.119209 -1.044236
2013-01-03 -0.861849 -2.104569 -0.494929  1.071804
2013-01-04  0.721555 -0.706771 -1.039575  0.271860
2013-01-05 -0.424972  0.567020  0.276232 -1.087401
2013-01-06 -0.673690  0.113648 -1.478427  0.524988

用 Series 字典对象生成 DataFrame:

In [9]: df2 = pd.DataFrame({'A': 1.,
   ...:                     'B': pd.Timestamp('20130102'),
   ...:                     'C': pd.Series(1, index=list(range(4)), dtype='float32'),
   ...:                     'D': np.array([3] * 4, dtype='int32'),
   ...:                     'E': pd.Categorical(["test", "train", "test", "train"]),
   ...:                     'F': 'foo'})
   ...:

In [10]: df2
Out[10]:
     A          B    C  D      E    F
0  1.0 2013-01-02  1.0  3   test  foo
1  1.0 2013-01-02  1.0  3  train  foo
2  1.0 2013-01-02  1.0  3   test  foo
3  1.0 2013-01-02  1.0  3  train  foo

DataFrame 的列有不同**数据类型open in new window**。

In [11]: df2.dtypes
Out[11]:
A           float64
B    datetime64[ns]
C           float32
D             int32
E          category
F            object
dtype: object

IPython支持 tab 键自动补全列名与公共属性。下面是部分可自动补全的属性:

In [12]: df2.<TAB>  # noqa: E225, E999
df2.A                  df2.bool
df2.abs                df2.boxplot
df2.add                df2.C
df2.add_prefix         df2.clip
df2.add_suffix         df2.clip_lower
df2.align              df2.clip_upper
df2.all                df2.columns
df2.any                df2.combine
df2.append             df2.combine_first
df2.apply              df2.compound
df2.applymap           df2.consolidate
df2.D

列 A、B、C、D 和 E 都可以自动补全;为简洁起见,此处只显示了部分属性。

#查看数据

下列代码说明如何查看 DataFrame 头部和尾部数据:

In [13]: df.head()
Out[13]:
                   A         B         C         D
2013-01-01  0.469112 -0.282863 -1.509059 -1.135632
2013-01-02  1.212112 -0.173215  0.119209 -1.044236
2013-01-03 -0.861849 -2.104569 -0.494929  1.071804
2013-01-04  0.721555 -0.706771 -1.039575  0.271860
2013-01-05 -0.424972  0.567020  0.276232 -1.087401

In [14]: df.tail(3)
Out[14]:
                   A         B         C         D
2013-01-04  0.721555 -0.706771 -1.039575  0.271860
2013-01-05 -0.424972  0.567020  0.276232 -1.087401
2013-01-06 -0.673690  0.113648 -1.478427  0.524988

显示索引与列名:

In [15]: df.index
Out[15]:
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
               '2013-01-05', '2013-01-06'],
              dtype='datetime64[ns]', freq='D')

In [16]: df.columns
Out[16]: Index(['A', 'B', 'C', 'D'], dtype='object')

DataFrame.to_numpy()open in new window 输出底层数据的 NumPy 对象。注意,DataFrameopen in new window 的列由多种数据类型组成时,该操作耗费系统资源较大,这也是 Pandas 和 NumPy 的本质区别:NumPy 数组只有一种数据类型,DataFrame 每列的数据类型各不相同。调用 DataFrame.to_numpy()open in new window 时,Pandas 查找支持 DataFrame 里所有数据类型的 NumPy 数据类型。还有一种数据类型是 object,可以把 DataFrame 列里的值强制转换为 Python 对象。

 总结

使用 Pandas 的 DataFrame,可以进行以下操作:加载和处理数据,包括 CSV、Excel、SQL 数据库等格式的数据进行数据清洗、重塑、切片和切块统计数据、计算聚合和汇总信息进行数据可视化将结果保存到各种格式的文件中将数据上传到数据库或在线应用程序、以其他格式输出数据,例如 HTML 表格。

Python中,我们可以使用Pandas库轻松地读取Excel文件,并结合Matplotlib或Seaborn等绘图库来创建图表展示各国的数据指标。以下是简单的步骤: 1. **安装必要的库**: 首先需要安装`pandas`和`openpyxl`(用于处理Excel文件),以及`matplotlib`或`seaborn`(用于绘制图形)。如果还没安装,可以使用以下命令: ```bash pip install pandas openpyxl matplotlib seaborn ``` 2. **导入所需库**: ```python import pandas as pd import matplotlib.pyplot as plt import seaborn as sns ``` 3. **读取Excel文件**: 假设您的Excel文件名为`data.xlsx`,并且有一个表格名为`countries_data`: ```python df = pd.read_excel('data.xlsx', sheet_name='countries_data') ``` 4. **预处理数据**: 确保数据已经清洗并整理好,例如设置国家名称作为索引: ```python df.set_index('Country', inplace=True) ``` 5. **选择要绘制的数据列**: 根据您的需求选择特定的指标列,比如`gdp`, `population`等: ```python data_columns = ['GDP', 'Population'] selected_data = df[data_columns] ``` 6. **绘制图表**: 使用`matplotlib`或`seaborn`绘制柱状图、线图或散点图等: - 对于简单比较,使用`barplot`或`stripplot`: ```python sns.barplot(x=data_columns, y=selected_data.index, data=selected_data) ``` - 或者,对于更复杂的关系,可以使用`lineplot`: ```python sns.lineplot(data=selected_data, x=data_columns[0], y=data_columns[1]) ``` 7. **显示和保存图表**: ```python plt.show() # 显示图形 plt.savefig('country_data_plot.png') # 保存为图片 ``` 完成以上步骤后,您就成功地从Excel文件中提取了数据,并通过Pandas和matplotlib/seaborn进行了可视化。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大锤爱编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值