【问题标题】:Converting a string number such as 31.1 M to a numeric / float?将诸如 31.1 M 之类的字符串数字转换为数字/浮点数?
【发布时间】:2021-02-21 22:15:47
【问题描述】:

我有一个数据框,其中有几列是字符串数据类型,其数字为“31.1 M”或“1.2 K”,分别代表 31,100,000 和 1,200。

我正在尝试将这些列转换为数字表示。我的挑战是在这些行中有'M'和'K'......我正在考虑应用for循环a)删除字符,然后根据字符(无论是'M'还是'K')相乘该因素的数量。然后转换为浮点数等。

关于如何解决这个问题的任何想法?这一个被难住了!

非常感谢, SS

【问题讨论】:

  • 查看您的行的 apply 函数。您可以编写一个 lambda 函数,它获取一个浮点数并根据 B、M、K 乘以它

标签: python string type-conversion


【解决方案1】:

您可以去掉逗号,将M 替换为e6,将K 替换为e3,然后转换为浮点数。

import pandas as pd

df = pd.DataFrame({'A': [1,2,3], 'B': ['1,200', '31.1 M', '1.2 K']})

B_new = (
    df.B.str.replace(',','')
        .str.replace('\s*M', 'e6')
        .str.replace('\s*K', 'e3')
        .astype(float)
)

B_new
# returns:
0        1200.0
1    31100000.0
2        1200.0
Name: B, dtype: float64

【讨论】:

  • 假设我在 df 中的列具有完全一样的字符串:31.42 M, 1.16 M, 5.2 K。我尝试了您拥有的代码并收到以下错误:ValueError: could not convert string to float: '--'.有什么想法吗?
  • 这意味着你在你的列中有字符串'--',它很可能代表0
【解决方案2】:

就个人而言,这可能是最简单的解决方案,但是如果没有任何代码可以使用,很难想出一个可以很好扩展的版本,应该主要关注速度:

string = '31.1 M'
value = float(string.replace('.', '').replace(' M', '000000'))
print(value)

【讨论】:

  • 这对于替换数据框列中的值不是一个很好的解决方案,因为它可能会删除所需的十进制标点符号。
  • 我不确定我理解你的意思。你能详细说明一下吗?
【解决方案3】:

我会编写一个带有参数的函数,您可以在以后对其进行扩展。

suffix_values = {'K': 1000, 'M':1000000}
def decode_string(string, suffix_values=suffix_values):
 # copy string to not modify the source
 _string = string[:]
 # if any keys in suffix_values exist in the string, replace it.
 for suffix in suffix_values:
     if suffix in string:
         value = suffix_values[suffix]
         _numeric = float(_string.replace(suffix, '').strip())*value
         return _numeric     

例子:

decode_string(suffix_values, '2.3M')
2300000.0

【讨论】:

    猜你喜欢
    • 2011-11-25
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    相关资源
    最近更新 更多