我正在尝试将数据集中某列中的每个值(例如100-120美元)转换为美元(有许多不同的货币,如欧元等),因此根据它们的货币,我需要使用相应的转换率进行转换。 我的输入文件如下所示:
d = {'location': ['US', 'UK'], 'price': ['USD10-20', 'GBP10-20']}
df = pd.DataFrame(data=d)
地点|价格
10-20美元
英国| 10-20英镑
等等
我试过这个:
def convertCurrency(price):
c=CurrencyConverter()
currency= price[0:3]
numbers=re.findall(r'\d+',price)
lowerbound= re.findall(r'\d+',price)[0]
res=""
upperbound='x'
if currency=='USD':
return price
if len(numbers)>1:
upperbound=numbers[1]
first=int(c.convert(int(lowerbound),price,"USD"))
if upperbound != 'x':
second=int(c.convert(int(upperbound),price,"USD"))
res=''+currency+str(first)+"-"+str(second)
else:
res = '' + currency + str(first)
return res
用apply来称呼它
df['price'] = df.apply(lambda row: convertCurrency(row.price), axis=1)
但这需要的时间太长了。 我也试过:
df['price'] = convertCurrency(df['price'])
但这将抛出一个错误,因为函数获取的是一个series对象而不是字符串。我必须改变什么,或者有其他方法吗? 我期望的结果是
地点|价格
10-20美元
英国| 14-28美元
让我们尝试使用extract获得可用值,然后在轴1上使用apply:
输出:
相关问题 更多 >
编程相关推荐