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