我有一个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)
该死,快速的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)