将货币值如€118.5M或€60K的pandas列转换为整数或浮点数

问题描述 投票:-5回答:1

我有一个CSV文件,其中包含一列值,如€118.5M或€60K,我需要将它们转换为整数或浮点数,然后进行计算。

import pandas as pd
file=pd.read_csv(r"C:\Users\muizv\Downloads\data (3).csv",index_col ="ID")
file[:10]
print(file)
python-3.x pandas
1个回答
0
投票

该死,快速的Google搜索发现:

def convert_si_to_number(x):
    total_stars = 0
    if 'k' in x:
        if len(x) > 1:
            total_stars = float(x.replace('k', '')) * 1000 # convert k to a thousand
    elif 'M' in x:
        if len(x) > 1:
            total_stars = float(x.replace('M', '')) * 1000000 # convert M to a million
    elif 'B' in x:
        total_stars = float(x.replace('B', '')) * 1000000000 # convert B to a Billion
    else:
        total_stars = int(x) # Less than 1000

    return int(total_stars)
© www.soinside.com 2019 - 2024. All rights reserved.