我有一个包含两列的 DataFrame:
df:
ix Col1 Col2
1 11.0 'JPY'
2 51.0 'EUR'
..
1000,000 27.0 'CAD'
我有一个货币列表 l1 = ['JPY','EUR',...,'CAD']
我有一个转换列表 l2 = [5.0, 1.0, ..., 0.5]
我也有一个我创建的函数:
def convert_currency(symbol, amount):
index_value = list_of_symbols.index(symbol)
rate = list_of_values[index_value]
converted = amount * rate
return converted
我想按如下方式应用此功能:
for index, row in df.iterrows():
if row['currency'] != 'GBP':
row['price_inc'] = convert_currency(row['currency'], row['price_inc'])
但它不起作用。
什么是基于 col2 值将函数应用于 col1 值的快速工作解决方案,并且该函数接收 col1 值并返回替换 col1 值的值
最佳答案
IIUC 您可以使用以下矢量化方法:
源数据集:
In [108]: d1
Out[108]:
ix Col1 Col2
0 1 11.0 JPY
1 2 51.0 EUR
2 3 27.0 CAD
In [109]: l1 = ['JPY','EUR','CAD']
In [110]: l2 = [5.0, 1.0, 0.5]
helper “汇率”系列:
In [111]: d2 = pd.Series(l2, l1)
In [112]: d2
Out[112]:
JPY 5.0
EUR 1.0
CAD 0.5
dtype: float64
解决方法:
In [113]: d1.Col1 *= d1.Col2.map(d2)
In [114]: d1
Out[114]:
ix Col1 Col2
0 1 55.0 JPY
1 2 51.0 EUR
2 3 13.5 CAD
关于python pandas DataFrame 遍历行并比较两列并应用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46228705/