首页 > 解决方案 > 带有美元符号的 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,因为它是一个错误。

对此的任何建议/帮助将不胜感激。谢谢你。

标签: pythonpandasnumeric

解决方案


过滤以 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

推荐阅读