python - 如何在熊猫中不使用 .apply 时将列的值相乘?
问题描述
我正在尝试将我的数据集列中的每个值(例如 100-120 美元)转换为美元(有许多不同的货币,如欧元等)所以根据他们的货币,我需要用各自的转换率来转换它们。我的输入文件是这样的:
d = {'location': ['US', 'UK'], 'price': ['USD10-20', 'GBP10-20']}
df = pd.DataFrame(data=d)
位置|价格
美国 |USD10-20
英国 |GBP10-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'])
但这会引发错误,因为该函数获取的是系列对象而不是字符串。我必须改变什么或有其他方法吗?我想要的结果将是
位置|价格
美国 |USD10-20
英国 |USD14-28
解决方案
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)
输出:
位置价格 0 美元 10-20 美元 1 英国 USD13-27
推荐阅读
- asp.net-web-api - 加载插件时如何在通用控制器上设置 api 版本?
- .net - 当我返回类型 HttpResponseMessage 时,示例值和模型在 swagger ui 中为空
- react-native - 如何从选项卡导航器中隐藏某个选项卡?
- xml - 检查值以在 SAPUI5 中设置“可见”
- tsql - 我的sql有3个游标,我觉得太多了,有没有更好的办法?
- python - 您如何使用 MultiplyNumeric 将日期转换为同一表的权重和值?
- mysql - 在sql查询中使用变量插入语句
- angular - 如何在有角度的谷歌地图信息窗口中添加的按钮上添加点击事件?
- python - 如何序列化 CSR 矩阵
- python - Panda.run_sql_query for where .. in .. 结构?