把数字翻译成字符串python,如何在Python中将以字符表示的数字转换为数字

I have a column in my data frame which has values like '3.456B' which actually stands for 3.456 Billion (and similar notation for Million). How to convert this string form to correct numeric representation?

This shows the data frame:

import pandas as pd

data_csv = pd.read_csv('https://biz.yahoo.com/p/csv/422conameu.csv')

data_csv

This is a sample value:

data_csv['Market Cap'][0]

type(data_csv['Market Cap'][0])

I tried this:

data_csv.loc[data_csv['Market Cap'].str.contains('B'), 'Market Cap'] = data_csv['Market Cap'].str.replace('B', '').astype(float).fillna(0.0)

data_csv

But unfortunately there are also values with 'M' at the end which denotes Millions. It returns error as follows:

ValueError: invalid literal for float(): 6.46M

How can I replace both B and M with appropriate values in this column? Is there a better way to do it?

解决方案

Assuming all entries have a letter at the end, you can do this:

d = {'K': 1000, 'M': 1000000, 'B': 1000000000}

df.loc[:, 'Market Cap'] = pd.to_numeric(df['Market Cap'].str[:-1]) * \

df['Market Cap'].str[-1].replace(d)

This converts everything but the last character into a numeric value, then multiplies it by the number equivalent to the letter in the last character.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值