pandas dataframe 如何把帶有千位分隔符的字符串轉化為浮點數


如何將下圖中的瀏覽量(PV)、訪客數(UV)、IP數這幾列中的帶有千位分隔符","的字符串類型轉換成浮點數類型

 

 

示例代碼如下:

import  pandas as pd
test  =  pd.DataFrame({ 'A' : [ '1,232.1' '22,332.3' '3,232' '1,111,111' ]})
print ( type (test.loc[ 0 , 'A' ]))
test1  =  pd.DataFrame({}).append(test)
  
test1[ 'A' =  test1[ 'A' ]. apply ( lambda  x: "".join(x.split( ',' ))).astype( 'float' )
print ( type (test1.loc[ 0 , 'A' ]))

 

實際代碼如下:

df['瀏覽量(PV)'= df.loc[:, '瀏覽量(PV)'].apply(lambda x: float(x.replace(",", "")))

或者:

df['瀏覽量(PV)'] = df.loc[:, '瀏覽量(PV)'].apply(lambda x: float(x.replace(",", "")) if "," in x else float(x))

import  pandas as pd
test  =  pd.DataFrame({ 'A' : [ '1,232.1' '22,332.3' '3,232' '1,111,111' ]})
print ( type (test.loc[ 0 , 'A' ]))
test1  =  pd.DataFrame({}).append(test)
  
test1[ 'A' =  test1[ 'A' ]. apply ( lambda  x: "".join(x.split( ',' ))).astype( 'float' )
print ( type (test1.loc[ 0 , 'A' ]))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM