如何使用 .replace 将 "string" 类型的 DataFrame 列转换为 "float"?
How do I convert DataFrame column of type "string" to "float" using .replace?
在我的 DataFrame 中,“Value_String”列由以下字符串组成:
- 以美元符号开头的类似数字的字符串,千位之间用逗号分隔,[例如1,000 美元]
- "None"
因此,我尝试创建一个新列并使用以下 lambda 函数将字符串转换为浮点数:
to_replace = '$,'
df['Value_Float'] = df[df['Value_String'].apply(lambda x: 0 if x == 'None'
else float(x.replace(y, '')) for y in to_replace)]
这实际上会生成“类型错误:'generator' 对象不可调用”。
我该如何解决这个问题?
numpy where
方法对于有条件地更新值非常有帮助。在这个值不是 'None' 的情况下,我们将使用替换函数。然而,由于 str.replace
默认使用正则表达式,我们需要将模式更改为文字美元符号或逗号
import pandas as pd
import numpy as np
df = pd.DataFrame({'Value_String':[",000","None"]})
df['Value_String'] = np.where(df['Value_String']!='None', df['Value_String'].str.replace('$|,',''), df['Value_String'])
print(df)
输出
Value_String
0 1000
1 None
在我的 DataFrame 中,“Value_String”列由以下字符串组成:
- 以美元符号开头的类似数字的字符串,千位之间用逗号分隔,[例如1,000 美元]
- "None"
因此,我尝试创建一个新列并使用以下 lambda 函数将字符串转换为浮点数:
to_replace = '$,'
df['Value_Float'] = df[df['Value_String'].apply(lambda x: 0 if x == 'None'
else float(x.replace(y, '')) for y in to_replace)]
这实际上会生成“类型错误:'generator' 对象不可调用”。
我该如何解决这个问题?
numpy where
方法对于有条件地更新值非常有帮助。在这个值不是 'None' 的情况下,我们将使用替换函数。然而,由于 str.replace
默认使用正则表达式,我们需要将模式更改为文字美元符号或逗号
import pandas as pd
import numpy as np
df = pd.DataFrame({'Value_String':[",000","None"]})
df['Value_String'] = np.where(df['Value_String']!='None', df['Value_String'].str.replace('$|,',''), df['Value_String'])
print(df)
输出
Value_String
0 1000
1 None