How to convert numbers represented as characters for short into numeric in Python

后端 未结 3 712
感动是毒
感动是毒 2020-12-20 16:54

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

3条回答
  •  眼角桃花
    2020-12-20 17:53

    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.

提交回复
热议问题