Pandas được Wes McKinney phát triển tại quỹ phòng hộ AQR để cho phép phân tích nhanh dữ liệu tài chính. Pandas là một phần mở rộng của NumPy hỗ trợ các hoạt động được vector hóa cho phép thao tác nhanh thông tin tài chính
Tôi sẽ sử dụng dữ liệu của công ty do hộp cát dành cho nhà phát triển Intrinio cung cấp. Nếu muốn làm theo, bạn có thể tìm thấy mã và dữ liệu trên Phân tích Alpha Github Repo
import pandas as pd
import numpy as np
import urllib.request
url= '//raw.githubusercontent.com/leosmigel ...
/analyzingalpha/master/2019-09-30-data-manipulation-with-python/companies.csv'
with urllib.request.urlopen[url] as f:
companies = pd.read_csv[f, index_col='id']
companies[['name', 'sector']].head[]
name sector
id
1 Apple Inc Consumer Goods
2 American Express Co Financial
3 Boeing Co Industrial Goods
4 Caterpillar Inc Industrial Goods
5 Cisco Systems Inc Technology
Làm cho dữ liệu của bạn gọn gàng
Mặc dù không cần thiết cho những ví dụ đơn giản này, nhưng tôi muốn giới thiệu Dữ liệu ngăn nắp. Khi làm việc với các tập dữ liệu lớn và đặc biệt là để phân tích nhân tố, bạn sẽ muốn làm cho cuộc sống của mình dễ dàng hơn và sắp xếp gọn gàng tập dữ liệu của mình bằng cách sử dụng pandas. tan chảy. Nó làm cho dữ liệu dễ phân tích hơn và thường hiệu quả hơn. Đối với những người quan tâm, có một bài viết tuyệt vời trên phương tiện về Bộ dữ liệu dọn dẹp trong Python
Hoạt động chuỗi trong Pandas
Thông thường, chúng ta sẽ cần thao tác với dữ liệu chuỗi được định dạng không chính xác. Pandas cung cấp [hoạt động chuỗi được vector hóa/trăn-cho-tài chính#vectorization]. Đối với hầu hết các phép toán chuỗi, bạn cần phải làm quen với biểu thức chính quy
Phương thứcMô tảgấu trúc. Loạt. str. chuỗi splitSplits trên các dấu phân cách được chỉ định. Loạt. str. replaceThay thế chuỗi khi khớp chuỗi hoặc regexpandas. Loạt. str. extractExtracts chuỗi trên khớp nhóm regexHãy thực hiện thao tác trích xuất ví dụ bằng cách kết hợp một số dữ liệu hiện có của chúng ta lại với nhau
companies_smushed = pd.DataFrame[]
companies_smushed['sector_employees'] = companies['sector'] + \
companies['employees'].astype[str]
print[companies[['sector', 'employees']].head[]]
print[companies_smushed.head[]]
companies_smushed = companies_smushed['sector_employees'].str.extract[r'[\D+][\d+]']
companies_smushed.head[]
sector employees
0 Consumer Goods 132000
1 Financial 59000
2 Industrial Goods 153027
3 Industrial Goods 104000
4 Technology 74200
sector_employees
0 Consumer Goods 132000
1 Financial 59000
2 Industrial Goods 153027
3 Industrial Goods 104000
4 Technology 74200
0 1
0 Consumer Goods 132000
1 Financial 59000
2 Industrial Goods 153027
3 Industrial Goods 104000
4 Technology 74200
Hoạt động nhóm. Tách-Áp dụng-Kết hợp
Hoạt động nhóm có thể được chia thành ba bước
- Chia dữ liệu thành các nhóm
- Áp dụng một chức năng cho mỗi nhóm
- Kết hợp các nhóm thành một kết quả
Trước khi chúng tôi sử dụng gấu trúc để nhóm và sửa đổi dữ liệu của mình, hãy xem cách chúng tôi có thể thực hiện việc đếm số lượng công ty trong từng lĩnh vực bằng cách sử dụng python
sector_count = {}
for sector in companies['sector']:
if sector_count.get[sector]:
sector_count.update[{sector: sector_count[sector] + 1}]
else:
sector_count.update[{sector: 1}]
print[sector_count]
{'Consumer Goods': 4,
'Financial': 5,
'Industrial Goods': 5,
'Technology': 5,
'Basic Materials': 2,
'Services': 3,
'Healthcare': 4}
nhóm
gấu trúc. Khung dữ liệu. groupby cung cấp cho chúng tôi cách tốt hơn để nhóm dữ liệu. groupby trả về đối tượng DataFrameGroupBy hoặc đối tượng SeriesGroupBy . Những đối tượng này có thể được coi là một nhóm. Bạn có thể thấy bên dưới sector_group. các nhóm trả về một từ điển gồm các cặp khóa/giá trị là các cung và các hàng được liên kết của chúng. Xem bên dưới nhóm tài chính chứa các hàng [[1, 6, 8, 14, 23]] tương ứng
sector_group = companies.groupby[by='sector']
print[sector_group]
print[sector_group.groups]
print[sector_group.get_group['Financial']]
{'Basic Materials': Int64Index[[5, 27], dtype='int64'],
'Consumer Goods': Int64Index[[0, 15, 20, 22], dtype='int64'],
'Financial': Int64Index[[1, 6, 8, 14, 23], dtype='int64'],
'Healthcare': Int64Index[[13, 18, 21, 24], dtype='int64'],
'Industrial Goods': Int64Index[[2, 3, 7, 12, 17], dtype='int64'],
'Services': Int64Index[[9, 16, 26], dtype='int64'],
'Technology': Int64Index[[4, 10, 11, 19, 25], dtype='int64']}
id name .. industry_group employees
1 2 American Express Co .. Credit Services 59000
6 25 Visa Inc .. Credit Services 17000
8 8 Goldman Sachs Group Inc .. Investment Brokerage - National 36600
14 13 JPMorgan Chase & Co .. Money Center Banks 256105
23 22 Travelers Companies Inc .. Property & Casualty Insurance 30400
[5 rows x 7 columns]
Để chỉ ra rằng đối tượng groupby chỉ là một bản thiết kế, chúng ta có thể sao chép get_group bằng cách sử dụng iloc
________số 8
name industry_group employees
1 American Express Co Credit Services 59000
6 Visa Inc Credit Services 17000
8 Goldman Sachs Group Inc Investment Brokerage - National 36600
14 JPMorgan Chase & Co Money Center Banks 256105
23 Travelers Companies Inc Property & Casualty Insurance 30400
Tóm lại, groupby tạo một kế hoạch chi tiết cho phép chúng tôi chạy nhiều hoạt động hữu ích trên nhóm. Sử dụng đối tượng nhóm theo nhóm hiệu quả vì nó cho phép chúng ta có mối quan hệ một-nhiều liên quan đến việc tính giá trị nhóm
Ngoài ra, chúng ta có thể sử dụng sức mạnh của Pandas và sử dụng lập chỉ mục boolean và phương pháp tổng hợp để trả về số lượng công ty trong từng lĩnh vực
tổng hợp
Tập hợp lấy các giá trị và trả về một giá trị của thứ nguyên nhỏ hơn. Ví dụ: một hàm nhận vào một chuỗi và trả về một giá trị vô hướng duy nhất. Mọi tập hợp GroupBy ngầm hoặc rõ ràng đều có một cột nhóm, một cột tổng hợp và một cột chức năng. Các chức năng tổng hợp phổ biến được hiển thị bên dưới
FunctionDescriptionmean[]Tính giá trị trung bình của nhómsum[]Tính tổng giá trị nhómsize[]Tính kích thước nhómcount[]Tính số lượng nhómstd[]Độ lệch chuẩn của nhómvar[]Tính phương sai của nhómsem[]Sai số chuẩn của giá trị trung bình nhómdescribe[]Tạo mô tả name sector
id
1 Apple Inc Consumer Goods
2 American Express Co Financial
3 Boeing Co Industrial Goods
4 Caterpillar Inc Industrial Goods
5 Cisco Systems Inc Technology
0 name sector
id
1 Apple Inc Consumer Goods
2 American Express Co Financial
3 Boeing Co Industrial Goods
4 Caterpillar Inc Industrial Goods
5 Cisco Systems Inc Technology
1Chúng ta cũng có thể nhóm theo nhiều cột. Lưu ý rằng hàm tổng hợp được gọi tự động trên cột nhân viên vì đây là cột loại số duy nhất
name sector
id
1 Apple Inc Consumer Goods
2 American Express Co Financial
3 Boeing Co Industrial Goods
4 Caterpillar Inc Industrial Goods
5 Cisco Systems Inc Technology
2 name sector
id
1 Apple Inc Consumer Goods
2 American Express Co Financial
3 Boeing Co Industrial Goods
4 Caterpillar Inc Industrial Goods
5 Cisco Systems Inc Technology
3gấu trúc. cốt lõi. theo nhóm. Khung dữ liệu. agg cho phép chúng tôi thực hiện nhiều thao tác tổng hợp cùng một lúc bao gồm cả các thao tác tổng hợp do người dùng xác định
name sector
id
1 Apple Inc Consumer Goods
2 American Express Co Financial
3 Boeing Co Industrial Goods
4 Caterpillar Inc Industrial Goods
5 Cisco Systems Inc Technology
4 name sector
id
1 Apple Inc Consumer Goods
2 American Express Co Financial
3 Boeing Co Industrial Goods
4 Caterpillar Inc Industrial Goods
5 Cisco Systems Inc Technology
5chuyển đổi
Chuyển đổi trả về dữ liệu được thao tác có cùng kích thước với dữ liệu đã truyền. Có nhiều phương thức và chức năng theo ý của bạn để chuyển đổi dữ liệu, như hình bên dưới
Phương thức/Chức năngDescriptionSeries. mapThay thế từng giá trị cho một sê-ri khác. applyInvoke một hàm theo nguyên tố trên một seriesDataFrame. applymapÁp dụng một chức năng theo nguyên tố cho một khung dữ liệuDataFrame. áp dụngGọi một chức năng trên mỗi cột hoặc hàngSeries. biến đổi Gọi một hàm trả về chuỗi giá trị được chuyển đổiDataFrame. biến đổi Gọi một hàm trả về khung dữ liệu của các giá trị được chuyển đổi. tan chảy Định hình lại một khung dữ liệu. Hữu ích cho việc vẽ đồ thị, hoạt động vector hóa và thu dọn dữ liệu. gấu trúc. pivot Định hình lại một khung dữ liệu. Về cơ bản là một hoạt động unmeltTrong ví dụ bên dưới, chúng tôi chuyển một hàm đã xác định find_percent và trả về chuỗi đã chuyển đổi
name sector
id
1 Apple Inc Consumer Goods
2 American Express Co Financial
3 Boeing Co Industrial Goods
4 Caterpillar Inc Industrial Goods
5 Cisco Systems Inc Technology
6 name sector
id
1 Apple Inc Consumer Goods
2 American Express Co Financial
3 Boeing Co Industrial Goods
4 Caterpillar Inc Industrial Goods
5 Cisco Systems Inc Technology
7Như với agg, chúng ta có thể truyền nhiều hàm, bao gồm cả hàm lambda
name sector
id
1 Apple Inc Consumer Goods
2 American Express Co Financial
3 Boeing Co Industrial Goods
4 Caterpillar Inc Industrial Goods
5 Cisco Systems Inc Technology
8 name sector
id
1 Apple Inc Consumer Goods
2 American Express Co Financial
3 Boeing Co Industrial Goods
4 Caterpillar Inc Industrial Goods
5 Cisco Systems Inc Technology
9Mặc dù chúng ta không thể chuyển nhiều hàm để áp dụng như với biến đổi, nhưng chúng ta có thể truy cập các cột khác bằng cách sử dụng áp dụng khi chúng ta bị giới hạn với biến đổi. Một lần nữa, tốt nhất là biết những gì có sẵn cho bạn và sử dụng công cụ tốt nhất cho công việc tại thời điểm hiện tại
companies_smushed = pd.DataFrame[]
companies_smushed['sector_employees'] = companies['sector'] + \
companies['employees'].astype[str]
print[companies[['sector', 'employees']].head[]]
print[companies_smushed.head[]]
companies_smushed = companies_smushed['sector_employees'].str.extract[r'[\D+][\d+]']
companies_smushed.head[]
0companies_smushed = pd.DataFrame[]
companies_smushed['sector_employees'] = companies['sector'] + \
companies['employees'].astype[str]
print[companies[['sector', 'employees']].head[]]
print[companies_smushed.head[]]
companies_smushed = companies_smushed['sector_employees'].str.extract[r'[\D+][\d+]']
companies_smushed.head[]
1lọc
Bộ lọc trả về một tập hợp con của dữ liệu gốc. Nó hoạt động tương tự như lập chỉ mục boolean ngoại trừ thay vì hoạt động trên các hàng riêng lẻ, nó hoạt động trên các nhóm riêng lẻ. Bộ lọc phải trả về giá trị Đúng hoặc Sai cho toàn bộ nhóm. Lĩnh vực dịch vụ là lĩnh vực duy nhất có hơn 1.000.000 nhân viên
companies_smushed = pd.DataFrame[]
companies_smushed['sector_employees'] = companies['sector'] + \
companies['employees'].astype[str]
print[companies[['sector', 'employees']].head[]]
print[companies_smushed.head[]]
companies_smushed = companies_smushed['sector_employees'].str.extract[r'[\D+][\d+]']
companies_smushed.head[]
2companies_smushed = pd.DataFrame[]
companies_smushed['sector_employees'] = companies['sector'] + \
companies['employees'].astype[str]
print[companies[['sector', 'employees']].head[]]
print[companies_smushed.head[]]
companies_smushed = companies_smushed['sector_employees'].str.extract[r'[\D+][\d+]']
companies_smushed.head[]
3Bảng tổng hợp
Chúng tôi có thể tạo cùng một dữ liệu ở định dạng khác bằng cách sử dụng gấu trúc. trục_bảng
companies_smushed = pd.DataFrame[]
companies_smushed['sector_employees'] = companies['sector'] + \
companies['employees'].astype[str]
print[companies[['sector', 'employees']].head[]]
print[companies_smushed.head[]]
companies_smushed = companies_smushed['sector_employees'].str.extract[r'[\D+][\d+]']
companies_smushed.head[]
4companies_smushed = pd.DataFrame[]
companies_smushed['sector_employees'] = companies['sector'] + \
companies['employees'].astype[str]
print[companies[['sector', 'employees']].head[]]
print[companies_smushed.head[]]
companies_smushed = companies_smushed['sector_employees'].str.extract[r'[\D+][\d+]']
companies_smushed.head[]
5tham gia dữ liệu
Chúng ta có thể nhanh chóng nối hai khung dữ liệu thông qua nối, hợp nhất và nối. Hợp nhất là chức năng cơ bản cho tất cả các hành vi tham gia/hợp nhất. Tham gia có các giá trị mặc định hơi khác và được cung cấp như một phương thức tiện lợi