我如何在没有应用程序的情况下乘以列的值?

2024-05-29 03:44:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将数据集中某列中的每个值(例如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美元


Tags: dfif货币res价格pricecurrencyint
1条回答
网友
1楼 · 发布于 2024-05-29 03:44:27

让我们尝试使用extract获得可用值,然后在轴1上使用apply

import pandas as pd
from currency_converter import CurrencyConverter

d = {'location': ['US', 'UK'], 'price': ['USD10-20', 'GBP10-20']}
df = pd.DataFrame(data=d)

c = CurrencyConverter()
# Extract Values
df[['currency', 'v1', 'v2']] = df['price'].str.extract(r'(\w{3})(\d+)-(\d+)',
                                                       expand=True)
# Mask For Non USD Currency
m = df['currency'].ne('USD')
# Replace price where not USD
df.loc[m, 'price'] = df[m].apply(
    lambda s: f'USD'
              f'{int(c.convert(int(s.v1), s.currency, "USD"))}'
              f'-'
              f'{int(c.convert(int(s.v2), s.currency, "USD"))}',
    axis=1
)
# Drop Added Columns
df = df.drop(columns=['currency', 'v1', 'v2'])
print(df)

输出:

  location     price
0       US  USD10-20
1       UK  USD13-27

相关问题 更多 >

    热门问题