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 格式檔案)中的字串資料替換為整數值的方法,並且在您有相同需求將資料欄位從字串更改為整數時,會出現很多情況。

更新於:2019年7月30日

778 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.