Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

pandas - How to convert numbers represented as characters for short into numeric in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'd use a dictionary to replace the strings then evaluate as float.

mapping = dict(K='E3', M='E6', B='E9')

df['Market Cap'] = pd.to_numeric(df['Market Cap'].replace(mapping, regex=True))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...