python - 带美元符号的 Pandas 数据框金额值

标签 python pandas numeric

我有一个包含以下几列的 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,因为这是一个错误。

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

最佳答案

Series.str.startswith 过滤以 $ 开头的值,通过 Series.str.strip 删除 $ 、转换为数字、舍入、转换为字符串并在前面添加 $:

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

关于python - 带美元符号的 Pandas 数据框金额值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61610258/

相关文章:

python - ftplib,如何在没有 errno 属性的情况下管理异常?

python - 这个 python 列表删除循环有什么问题?

python - 使用 for 循环创建一个 DF 时,Pandas concat 无法按预期工作

python - 如何向量化基于最后 x 行数据的 Pandas 计算

c - 无法找到导致此错误的原因

java - 输入数字进入下一行,但输入非数字时出现异常

python - 图像分类任务的损失为 NaN

python - Pandas 枢轴 : how to keep rows with all NaNs without introducing extra rows

c - 根据 C 标准,负整数文字是解释为单个文字,还是运算符和文字?

python - keras中的概率回归