Đôi khi trong phân tích dữ liệu cần chuyển đổi chuỗi thành số (int/float). Với mỗi chuỗi, ta gán một giá trị nguyên duy nhất để phân biệt các giá trị chuỗi.
Sử dụng dữ liệu trong file CSV (Comma Separated Values). Giả sử có file Excel chứa dữ liệu CSV như sau:
| Company | Industry | Recommendation |
|---|---|---|
| HDFC Bank | Finance | Hold |
| Apollo | Healthcare | Buy |
| Hero | Automobile | Underperform |
| Yes Bank | Finance | Hold |
| M&M | Automobile | Underperform |
| Fortis | Healthcare | Buy |
| Maruti | Automobile | Underperform |
Đây chỉ là một vài dòng từ tập dữ liệu lớn. Cần gán giá trị nguyên cho các khuyến nghị (Buy, Hold, Underperform) để liên kết với metadata. Kết quả mong đợi:
| Company | Industry | Recommendation |
|---|---|---|
| HDFC Bank | Finance | 2 |
| Apollo | Healthcare | 1 |
| Hero | Automobile | 3 |
| Yes Bank | Finance | 2 |
| M&M | Automobile | 3 |
| Fortis | Healthcare | 1 |
| Maruti | Automobile | 3 |
Cách thay thế giá trị chuỗi (cột) bằng số nguyên:
Cách 1: Sử dụng Dictionary
import pandas as pd
# Đọc file CSV vào DataFrame
dataframe = pd.read_csv("data_pandas1.csv")
# Tạo dictionary ánh xạ giá trị cũ (chuỗi) -> giá trị mới (số nguyên)
Recommendation = {'Buy': 1, 'Hold': 2, 'Underperform': 3}
# Ánh xạ các cặp key-value từ dictionary vào cột của DataFrame
dataframe.Recommendation = [Recommendation[item] for item in dataframe.Recommendation]
# In DataFrame mới
print(dataframe)
Kết quả
Company Industry Recommendation
0 HDFC Bank Finance 2
1 Apollo Healthcare 1
2 Hero Automobile 3
3 Yes Bank Finance 2
4 M&M Automobile 3
5 Fortis Healthcare 1
6 Maruti Automobile 3
Cách 2: Gán trực tiếp theo điều kiện
import pandas as pd
dataf = pd.read_csv("data_pandas1.csv")
# Gán trực tiếp giá trị số cho cột Recommendation nếu điều kiện khớp
dataf.Recommendation[dataf.Recommendation == 'Buy'] = 1
dataf.Recommendation[dataf.Recommendation == 'Hold'] = 2
dataf.Recommendation[dataf.Recommendation == 'Underperform'] = 3
print(dataf)
Kết quả
Company Industry Recommendation
0 HDFC Bank Finance 2
1 Apollo Healthcare 1
2 Hero Automobile 3
3 Yes Bank Finance 2
4 M&M Automobile 3
5 Fortis Healthcare 1
6 Maruti Automobile 3
Trên đây là hai cách phổ biến để chuyển đổi dữ liệu chuỗi trong bảng (file CSV) sang giá trị nguyên. Trong thực tế có nhiều tình huống tương tự cần thay đổi trường dữ liệu từ chuỗi sang số.