在 pandas 数据框中将数字和字母的字符串转换为int/float [英] Converting string of numbers and letters to int/float in pandas dataframe

查看:80
本文介绍了在 pandas 数据框中将数字和字母的字符串转换为int/float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得必须快速解决我的问题,我使用多个列表推导方法破解了一个实施不佳的解决方案,但这并不理想.也许有人可以在这里帮忙.

I feel like there has to be a quick solution to my problem, I hacked out a poorly implemented solution using multiple list comprehensions which is not ideal whatsoever. Maybe someone could help out here.

我有一组字符串值(例如3.2B,1.5M,1.1T),其中最后一个字符自然表示一百万,十亿,万亿.在该集合内,还应保留NaN/'none'值.我希望将它们转换为浮点数或整数,因此在给定的示例中(3200000000、1500000、1100000000000)

I have a set of values which are strings (e.g. 3.2B, 1.5M, 1.1T) where naturally the last character denotes million, billion, trillion. Within the set there are also NaN/'none' values which should remain untouched. I wish to convert these to floats or ints, so in the given example (3200000000, 1500000, 1100000000000)

TIA

推荐答案

您可以创建一个函数:和

You could create a function: and applymap it to every entry in the dataframe:

powers = {'B': 10 ** 9, 'M': 10 ** 6, 'T': 10 ** 12}
# add some more to powers as necessary

def f(s):
    try:
        power = s[-1]
        return int(s[:-1]) * powers[power]
    except TypeError:
        return s

df.applymap(f)

这篇关于在 pandas 数据框中将数字和字母的字符串转换为int/float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆