本文采用真实的股票数据作为案例,教你如何在Python中读取常用的数据文件。
内容:
- 读取csv数据
- 读取Excel数据
- 合并多张表
数据文件下载地址:
读取csv数据
csv文件用逗号来分隔数值,是常用的数据格式之一,其具体形式可参考上面给出的数据文件。接下来我们将使用 Python 中的 pandas 数据分析包来进行数据的读取和查看。
pandas.read_csv()
: 读取csv格式数据,并存储成数据框 DataFrame 格式。df.head()
: 显示数据框 df 的前5行。df.info()
: 显示数据摘要。
# 导入pandas包
import pandas as pd
# 读取csv文件
nasdaq = pd.read_csv('nasdaq-listings.csv')
# 显示前10行数据
print(nasdaq.head(10))
Stock Symbol Company Name Last Sale Market Capitalization \
0 AAPL Apple Inc. 141.05 7.400000e+11
1 GOOGL Alphabet Inc. 840.18 5.810000e+11
2 GOOG Alphabet Inc. 823.56 5.690000e+11
3 MSFT Microsoft Corporation 64.95 5.020000e+11
4 AMZN Amazon.com, Inc. 884.67 4.220000e+11
5 FB Facebook, Inc. 139.39 4.030000e+11
6 CMCSA Comcast Corporation 37.14 1.760000e+11
7 INTC Intel Corporation 35.25 1.660000e+11
8 CSCO Cisco Systems, Inc. 32.42 1.620000e+11
9 AMGN Amgen Inc. 161.61 1.190000e+11
IPO Year Sector \
0 1980 Technology
1 NAN Technology
2 2004 Technology
3 1986 Technology
4 1997 Consumer Services
5 2012 Technology
6 NAN Consumer Services
7 NAN Technology
8 1990 Technology
9 1983 Health Care
Industry Last Update
0 Computer Manufacturing 4/26/17
1 Computer Software: Programming, Data Processing 4/24/17
2 Computer Software: Programming, Data Processing 4/23/17
3 Computer Software: Prepackaged Software 4/26/17
4 Catalog/Specialty Distribution 4/24/17
5 Computer Software: Programming, Data Processing 4/26/17
6 Television Services 4/26/17
7 Semiconductors 4/23/17
8 Computer Communications Equipment 4/23/17
9 Biotechnology: Biological Products (No Diagnos... 4/24/17
使用 .info()
方法,可查看数据框的摘要信息。
# 查看数据摘要
nasdaq.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1115 entries, 0 to 1114
Data columns (total 8 columns):
Stock Symbol 1115 non-null object
Company Name 1115 non-null object
Last Sale 1115 non-null float64
Market Capitalization 1115 non-null float64
IPO Year 1115 non-null object
Sector 1115 non-null object
Industry 1115 non-null object
Last Update 1115 non-null object
dtypes: float64(2), object(6)
memory usage: 69.8+ KB
从上面列出的信息可知,这份纳斯达克股票数据包括股票代码(Stock Symbol),公司名(Company Name),价格(Last Sale),市值(Market Capitalization),IPO年份(IPO Year), 行业(Sector), 产业(Industry),更新时间(Last Update)这8列。
读取的数据需要能还原原始数据中的信息,比如 Last Update
应该是时间格式的数据,而在 IPO Year
中存在 NAN这类缺失的数值,这些目前都没有反应出来。所以下面需要设置参数,改进csv文件的读取方式。
pandas.read_csv()
参数
- na_vlaues: 设置缺失值形式。
- parse_dates: 将指定的列解析成时间日期格式。
nasdaq = pd.read_csv('nasdaq-listings.csv', na_values='NAN', parse_dates=['Last Update'])
print(nasdaq.head())
Stock Symbol Company Name Last Sale Market Capitalization \
0 AAPL Apple Inc. 141.05 7.400000e+11
1 GOOGL Alphabet Inc. 840.18 5.810000e+11
2 GOOG Alphabet Inc. 823.56 5.690000e+11
3 MSFT Microsoft Corporation 64.95 5.020000e+11
4 AMZN Amazon.com, Inc. 884.67 4.220000e+11
IPO Year Sector \
0 1980.0 Technology
1 NaN Technology
2 2004.0 Technology
3 1986.0 Technology
4 1997.0 Consumer Services
Industry Last Update
0 Computer Manufacturing 2017-04-26
1 Computer Software: Programming, Data Processing 2017-04-24
2 Computer Software: Programming, Data Processing 2017-04-23
3 Computer Software: Prepackaged Software 2017-04-26
4 Catalog/Specialty Distribution 2017-04-24
nasdaq.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1115 entries, 0 to 1114
Data columns (total 8 columns):
Stock Symbol 1115 non-null object
Company Name 1115 non-null object
Last Sale 1115 non-null float64
Market Capitalization 1115 non-null float64
IPO Year 593 non-null float64
Sector 1036 non-null object
Industry 1036 non-null object
Last Update 1115 non-null datetime64[ns]
dtypes: datetime64[ns](1), float64(3), object(4)
memory usage: 69.8+ KB
读取Excel数据
Excel文件是传统的数据格式,但面对海量数据时,用编程的方法来处理数据更有优势。这里示例用的数据文件如下图所示,注意它有3张sheet表。
类似于csv文件,可以使用 pandas.read_excel()
函数来读取 Excel 文件,并存储成数据框格式。
pandas.read_excel() 读取 Excel 文件,其参数如下:
- sheet_name: 设置读取的 sheet 名。
- na_values: 设置缺失值的形式。
# 读取Excel数据,选取nyse这一页
nyse = pd.read_excel('listings.xlsx', sheet_name='nyse', na_values='n/a')
# 显示前几行
print(nyse.head())
Stock Symbol Company Name Last Sale Market Capitalization \
0 DDD 3D Systems Corporation 14.48 1.647165e+09
1 MMM 3M Company 188.65 1.127366e+11
2 WBAI 500.com Limited 13.96 5.793129e+08
3 WUBA 58.com Inc. 36.11 5.225238e+09
4 AHC A.H. Belo Corporation 6.20 1.347351e+08
IPO Year Sector \
0 NaN Technology
1 NaN Health Care
2 2013.0 Consumer Services
3 2013.0 Technology
4 NaN Consumer Services
Industry
0 Computer Software: Prepackaged Software
1 Medical/Dental Instruments
2 Services-Misc. Amusement & Recreation
3 Computer Software: Programming, Data Processing
4 Newspapers/Magazines
# 显示摘要信息
nyse.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3147 entries, 0 to 3146
Data columns (total 7 columns):
Stock Symbol 3147 non-null object
Company Name 3147 non-null object
Last Sale 3079 non-null float64
Market Capitalization 3147 non-null float64
IPO Year 1361 non-null float64
Sector 2177 non-null object
Industry 2177 non-null object
dtypes: float64(3), object(4)
memory usage: 172.2+ KB
这里其实只读取了一张sheet表,但是该Excel文件一共有三张sheet表,下面将演示如何读取所有的sheet表。
pd.ExcelFile()
:将 Excel 文件存储成 ExcelFile 对象。ExcelFile.sheet_names
: 获取ExcelFile的所有sheet表的名称,存储在python列表中。
# 将Excel文件读取成 ExcelFile 格式
xls = pd.ExcelFile('listings.xlsx')
# 获取sheet表的名称
exchanges = xls.sheet_names
print(exchanges)
['amex', 'nasdaq', 'nyse']
然后仍然使用 pd.read_excel()
读取 ExcelFile 数据,但传递给参数 sheet_name 的值是上述 exchanges 列表。返回值 listings 是字典格式,每一个元素对应的是一张表的DataFrame。
# 读取所有sheet的数据,存储在字典中
listings = pd.read_excel(xls, sheet_name=exchanges, na_values='n/a')
# 查看 nasdaq 表的摘要信息
listings['nasdaq'].info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3167 entries, 0 to 3166
Data columns (total 7 columns):
Stock Symbol 3167 non-null object
Company Name 3167 non-null object
Last Sale 3165 non-null float64
Market Capitalization 3167 non-null float64
IPO Year 1386 non-null float64
Sector 2767 non-null object
Industry 2767 non-null object
dtypes: float64(3), object(4)
memory usage: 173.3+ KB
合并多张表
现在我们希望将Excel中的多张表合并在一起,由于他们具有相同的列结构,所以可以进行简单的堆叠。下面将 nyse 和 nasdaq 这两张表连接在一起,使用 pd.concat()
函数。
pd.concat()
函数用于连接多个DataFrame数据框,注意这些被合并的DataFrame需要放在列表中。
# 读取 nyse 和nasdaq 这两张表的数据
nyse = pd.read_excel('listings.xlsx', sheet_name='nyse', na_values='n/a')
nasdaq = pd.read_excel('listings.xlsx', sheet_name='nasdaq', na_values='n/a')
# 添加一列 Exchange,标记来自哪张表的数据
nyse['Exchange'] = 'NYSE'
nasdaq['Exchange'] = 'NASDAQ'
# 拼接两个DataFrame
combined_listings = pd.concat([nyse, nasdaq]) # 注意这里的[ ]
combined_listings.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 6314 entries, 0 to 3166
Data columns (total 8 columns):
Stock Symbol 6314 non-null object
Company Name 6314 non-null object
Last Sale 6244 non-null float64
Market Capitalization 6314 non-null float64
IPO Year 2747 non-null float64
Sector 4944 non-null object
Industry 4944 non-null object
Exchange 6314 non-null object
dtypes: float64(3), object(5)
memory usage: 444.0+ KB
如果要合并所有的表,我们同样可以通 ExcelFile.sheet_names
来获取所有的sheet表的名称,然后通过循环读取每一个sheet表的数据,最后使用 pd.concat()
函数来合并所有sheet表。
# 创建 ExcelFile 变量
xls = pd.ExcelFile('listings.xlsx')
# 获取sheet名
exchanges = xls.sheet_names
# 创建空列表
listings = []
# 使用循环逐一导入每一页的数据,并存储在列表中
for exchange in exchanges:
listing = pd.read_excel(xls, sheet_name=exchange, na_values='n/a')
listing['Exchange'] = exchange
listings.append(listing)
# 合并数据
listing_data = pd.concat(listings)
# 查看合并后数据的摘要
listing_data.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 6674 entries, 0 to 3146
Data columns (total 8 columns):
Stock Symbol 6674 non-null object
Company Name 6674 non-null object
Last Sale 6590 non-null float64
Market Capitalization 6674 non-null float64
IPO Year 2852 non-null float64
Sector 5182 non-null object
Industry 5182 non-null object
Exchange 6674 non-null object
dtypes: float64(3), object(5)
memory usage: 469.3+ KB
注:本文是 DataCamp 课程 Importing & Managing Financial Data in Python
的学习笔记。更多该课程的文章:
网友评论