将具有 1.185 亿欧元或 6 万欧元等货币值的 pandas 列转换为整数或浮点数
Convert pandas column with currency values like €118.5M or €60K to integers or floats
我有一个 CSV 文件,其中有一列的值类似于 1.185 亿欧元或 6 万欧元,我需要将这些值转换为整数或浮点数,然后进行计算。
import pandas as pd
file = pd.read_csv("data.csv",index_col ="ID")
file[:10]
print(file)
1.185 亿欧元
....
6 万欧元
该死,快速 google 搜索发现:
def convert_si_to_number(x):
total_stars = 0
x = x.replace('€', '')
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)
一个简单的应用到 df 的方法是 运行 它在循环中
for i, stringo in enumerate(file):
file[i] = convert_si_to_number(stringo)
我有一个 CSV 文件,其中有一列的值类似于 1.185 亿欧元或 6 万欧元,我需要将这些值转换为整数或浮点数,然后进行计算。
import pandas as pd
file = pd.read_csv("data.csv",index_col ="ID")
file[:10]
print(file)
1.185 亿欧元
....
6 万欧元
该死,快速 google 搜索发现:
def convert_si_to_number(x):
total_stars = 0
x = x.replace('€', '')
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)
一个简单的应用到 df 的方法是 运行 它在循环中
for i, stringo in enumerate(file):
file[i] = convert_si_to_number(stringo)