如何将下图中的浏览量(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‘
]))
原文地址:https://www.cnblogs.com/meicq/p/11038260.html
时间: 2024-11-05 21:36:59