python - 将 a/b 字符串转换为在 pandas 中 float

标签 python string pandas dataframe

我有这样的数据框:

        score  year
         5/5   2019
         1/2   2018
          A    2019

我想将分数从字符串转换为 float ,例如 5/5=1、1/2=0.5,我尝试使用 to_numeric,但由于我的值是 a/b 形式,所以它没有返回任何值。请帮我解决这个问题。

最佳答案

您可以使用 pandas.eval使用 try-except 语句:

def func(x):
    try:
        return pd.eval(x)
    except Exception:
        #for return original
        return x
        #for return None
        #return None

df['new'] = df['score'].apply(func)
print (df)
  score  year  new
0   5/5  2019    1
1   1/2  2018  0.5
2     A  2019    A

如果只有除法是来自@Goyo 的更快的解决方案,谢谢:

import operator

def func(x):
    try:
        return operator.truediv(*map(int, x.split('/')))
    except Exception:
        #for return original
        return x
        #for return None
        #return None

关于python - 将 a/b 字符串转换为在 pandas 中 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55059365/

相关文章:

python - 使用羽化格式包出错

Python - beautifulsoup,应用于文件夹中的每个文本文件并生成新的文本文件

python - 填补 MultiIndex Pandas Dataframe 中的日期空白

python - 通过对数据进行分组来汇总 pandas 中的数据

python - 删除附加到单词的所有数字 - Python

c - 字符数组的未定义长度

python - 如何获取多索引数据框前两个索引的字典

python - 如何检查 Cerberus 中的引用完整性?

python - 为什么 Django-simple-math-captcha 不呈现问题?

python - 查找并剪切出一个python子串