python - 带有美元符号的 Pandas 数据框金额值
问题描述
我有一个带有以下列的熊猫数据框。Column_1 是字符串/文本,而不是整数或小数。几行具有字符串值以及名称(请参阅第 6 行)
S.No. Column_1
1 256
2 1
3 $300.54672
4 756
5 $292.34333
6 Andrew
我想将 column_1 中的所有值转换为数字/整数,但美元值和带有名称的行除外。我要求保留美元符号,但金额应四舍五入至小数点后 2 位。
预期输出:
S.No. Column_1
1 256
2 1
3 $300.55
4 756
5 $292.34
6 Andrew
我使用带有 errors='coerce' 的 pd.to_numeric() 将整列转换为数字,但数量值变为空白(或)null,因为它是一个错误。
对此的任何建议/帮助将不胜感激。谢谢你。
解决方案
过滤以 by 开头的值$
,Series.str.startswith
删除$
by Series.str.strip
,转换为数字,四舍五入,转换为字符串和 prepend $
:
m = df['Column_1'].str.startswith('$', na=False)
s = '$' + df.loc[m, 'Column_1'].str.strip('$').astype(float).round(2).astype(str)
或者:
s = df.loc[m, 'Column_1'].str.strip('$').astype(float).round(2).astype(str).radd('$')
df.loc[m, 'Column_1'] = s
print (df)
S.No. Column_1
0 1 256
1 2 1
2 3 $300.55
3 4 756
4 5 $292.34
最后,如果需要将不匹配的值转换为数字,但获得混合数据类型 - 带有的字符串$
和不带的数字$
:
df.loc[~m, 'Column_1'] = pd.to_numeric(df.loc[~m, 'Column_1'])
print (df)
S.No. Column_1
0 1 256
1 2 1
2 3 $300.54672
3 4 756
4 5 $292.34333
print (df['Column_1'].apply(type))
0 <class 'int'>
1 <class 'int'>
2 <class 'str'>
3 <class 'int'>
4 <class 'str'>
Name: Column_1, dtype: object
编辑最后一段:这里可以添加errors='coerce'
将非数字转换为缺失值,然后用原始值替换它们:
df.loc[~m, 'Column_1'] = pd.to_numeric(df.loc[~m, 'Column_1'], errors='coerce').fillna(df['Column_1'])
print (df)
S.No. Column_1
0 1 256
1 2 1
2 3 $300.55
3 4 756
4 5 $292.34
5 6 Andrew
print (df['Column_1'].apply(type))
0 <class 'float'>
1 <class 'float'>
2 <class 'str'>
3 <class 'float'>
4 <class 'str'>
5 <class 'str'>
Name: Column_1, dtype: object
推荐阅读
- oracle - Oracle 外键约束 - 检查约束语法?
- asp.net-mvc - MVC Jquery 数据表不工作
- angular - 在 zone.js 中随机获取超过最大调用堆栈大小
- python - 为什么使用类方法而不是只使用类名作为实例?
- d3.js - 有没有办法改变鼠标悬停时的c3js堆积面积图不透明度
- sendkeys - Pywinauto Sendkeys 函数
- .net - 如何在多线程函数中修改全局数组
- mysql - mysql在一个月内每天获取客户端的平均值
- tensorflow - 初始化权重的值应该是多少
- python - 创建一个新函数或只是普通打印以从另一个函数中获取值