有时在数据分析中需要将字符串转换为数字(整数/浮点数)。对于每个字符串,我们可以分配一个唯一的整数值来区分字符串值。
为此,我们使用逗号分隔值(CSV)文件中的数据。假设我们有一个包含CSV数据的Excel文件,如下所示-
| 公司 | 行业 | 建议 |
|---|---|---|
| HDFC银行 | 金融 | 保持 |
| 阿波罗 | 卫生保健 | 购买 |
| 英雄 | 汽车 | 表现不佳 |
| 是的银行 | 金融 | 保持 |
| 并购 | 汽车 | 表现不佳 |
| 富通 | 卫生保健 | 购买 |
| 马鲁蒂 | 汽车 | 表现不佳 |
上面只是来自大型数据集的几行,我们需要给出不同的建议,即买入,持有,表现不佳等整数值,它们将链接到我们的元数据。因此,对于上述输入,我们的预期输出将类似于-
| 公司 | 行业 | 建议 |
|---|---|---|
| HDFC银行 | 金融 | 2 |
| 阿波罗 | 卫生保健 | 1 |
| 英雄 | 汽车 | 3 |
| 是的银行 | 金融 | 2 |
| 并购 | 汽车 | 3 |
| 富通 | 卫生保健 | 1 |
| 马鲁蒂 | 汽车 | 3 |
这是将我们的字符串(列值)替换为整数的一种方法。
#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
还有另一种编写上述代码的方法,如果条件匹配,我们不处理字典,而是直接将另一个值分配给column字段(此处为建议)。
#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格式文件)中的字符串数据替换为整数值的唯一方法,当您有相同的要求将数据字段从字符串更改为整数时,就会出现很多实例。