Python 数据分析中用数字替换字符串
有时在数据分析中需要将字符串转换为数字(整数/浮点数)。对于每个字符串,我们可以分配一个唯一的整数值来区分字符串值。
为此,我们使用逗号分隔值 (CSV) 文件中的数据。假设我们有一个包含以下 CSV 数据的 Excel 文件:
| 公司 | 行业 | 建议 |
|---|---|---|
| HDFC 银行 | 金融 | 持有 |
| 阿波罗 | 医疗保健 | 买入 |
| 英雄 | 汽车 | 表现不佳 |
| Yes 银行 | 金融 | 持有 |
| M&M | 汽车 | 表现不佳 |
| Fortis | 医疗保健 | 买入 |
| 马鲁蒂 | 汽车 | 表现不佳 |
以上只是大型数据集中的几行,我们需要为不同的建议(例如买入、持有、表现不佳等)分配整数值,这些整数值将链接到我们的元数据。因此,对于上述输入,我们预期的输出将类似于:
| 公司 | 行业 | 建议 |
|---|---|---|
| HDFC 银行 | 金融 | 2 |
| 阿波罗 | 医疗保健 | 1 |
| 英雄 | 汽车 | 3 |
| Yes 银行 | 金融 | 2 |
| M&M | 汽车 | 3 |
| Fortis | 医疗保健 | 1 |
| 马鲁蒂 | 汽车 | 3 |
以下是如何将我们的字符串(列值)替换为整数。
代码 1
#Import required library
import pandas as pd
#Import the CSV file into Python using read_csv() from pandas
dataframe = pd.read_csv("data_pandas1.csv")
#Create the dictionary of key-value pair, where key is
#your old value(string) and value is your new value(integer).
Recommendation = {'Buy': 1, 'Hold': 2, 'Underperform': 3}
#Assign these different key-value pair from above dictiionary to your table
dataframe.Recommendation = [Recommendation[item] for item in dataframe.Recommendation]
#New table
print(dataframe)结果
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
还有另一种编写上述代码的方法,我们不使用字典,而是直接在条件匹配时为列字段(此处为“建议”)分配另一个值。
#Import required library
import pandas as pd
#Import the CSV file into Python using read_csv() from pandas
dataf = pd.read_csv("data_pandas1.csv")
#Directly assigning individual fields of Recommendation column different integer value
#if condition matches .i.e.In the dataframe, recommendation columns we have "Buy" we'll assign
# integer 1 to it.
dataf.Recommendation[data.Recommendation =='Buy'] =1
dataf.Recommendation[data.Recommendation =='Hold'] =2
dataf.Recommendation[data.Recommendation =='Underperform'] =3
print(dataf)结果
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
在上面,我提到了两种将表(csv 格式文件)中的字符串数据替换为整数值的方法,并且在您有相同需求将数据字段从字符串更改为整数时,会出现很多情况。
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP