在单独的 Dataframe 中相乘列

roqulrg3  于 2021-09-08  发布在  Java
关注(0)|答案(2)|浏览(326)

我试图将来自2个不同 Dataframe 的数据相乘,我的代码如下:

import pandas as pd
import numpy as np

df1 = pd.DataFrame({'v_contract_number': ['VN120001438','VN120001439',
                                          'VN120001440','VN120001438',
                                          'VN120001439','VN120001440'],
                                            'Currency': ['VND','USD','KRW','USD','KRW','USD'],
                                        'Amount': [10000,5000,6000,200,150,175]})
df2 = pd.DataFrame({'Currency': ['VND','USD','KRW'],'Rate': [1,23000,1200]})
print(df1)

# df1

  v_contract_number Currency  Amount
0       VN120001438      VND   10000
1       VN120001439      USD    5000
2       VN120001440      KRW    6000
3       VN120001438      USD     200
4       VN120001439      KRW     150
5       VN120001440      USD     175

print(df2)
  Currency   Rate
0      VND      1
1      USD  23000
2      KRW   1200

df1 = df1.merge(df2)
df1['VND AMount'] = df1['Amount'].mul(df1['Rate'])
df1.drop('Rate', axis=1, inplace=True)
print(df1)

# result

  v_contract_number Currency  Amount  VND AMount
0       VN120001438      VND   10000       10000
1       VN120001439      USD    5000   115000000
2       VN120001438      USD     200     4600000
3       VN120001440      USD     175     4025000
4       VN120001440      KRW    6000     7200000
5       VN120001439      KRW     150      180000

这正是我想要的,但我想知道,有没有其他方法不合并和删除,因为我做了?我之所以放弃“利率”,是因为我不希望它出现在我的报告中。
谢谢并致以最良好的问候

mepcadol

mepcadol1#

您可以使用PandasMap进行以下操作:

df2 = df2.set_index('Currency').squeeze() # squeeze converts to a Series

df1.assign(VND_Amount = df1.Amount.mul(df1.Currency.map(df2)))

  v_contract_number Currency  Amount  VND_Amount
0       VN120001438      VND   10000       10000
1       VN120001439      USD    5000   115000000
2       VN120001440      KRW    6000     7200000
3       VN120001438      USD     200     4600000
4       VN120001439      KRW     150      180000
5       VN120001440      USD     175     4025000
kd3sttzy

kd3sttzy2#

您可以通过不覆盖来避免删除 df1 在合并操作中:

df1["VND Amount"] = df1.merge(df2, on="Currency").eval("Amount * Rate")

或者,您可以使用 .reindex 要根据货币列将df2与df1对齐,请执行以下操作:

df1["VND Amount"] = (
    df1["Amount"] * 
    (df2.set_index("Currency")["Rate"]  # set the index and return Rate column
        .reindex(df1["Currency"])       # align "Rate" values to df1 "Currency"
        .to_numpy()                     # get numpy array to avoid pandas 
                                        #   auto alignment on math ops
    )
)

相关问题