在 pandas 中使用 .apply() 时如何将内容从一列复制到另一列?

How do I copy contents from one column to another while using .apply() in pandas?

我有一个包含 2 列 total_open_amountinvoice_currency 的 DataFrame。

invoice_currency

USD    45011
CAD     3828
Name: invoice_currency, dtype: int64

我想将 total_open_amount 列中的所有 CAD 转换为 USD 到 invoice_currency,汇率为 1 CAD = 0.7USD,并将它们存储在单独的列中。

我的代码:

df_data['converted_usd'] = df_data['total_open_amount'].where(df_data['invoice_currency']=='CAD')
df_data['converted_usd']= df_data['converted_usd'].apply(lambda x: x*0.7)
df_data['converted_usd']

输出:

0            NaN
1            NaN
2            NaN
3        2309.79
4            NaN
          ...   
49995        NaN
49996        NaN
49997        NaN
49998        NaN
49999        NaN
Name: converted_usd, Length: 48839, dtype: float64

我可以用转换后的加元值填充新列,但现在如何填充其余的美元值?

我们可以使用 Series.mask or Series.where, series.mask'invoice_currency' 为 USD 的行设置为 NaN,但是使用 other 参数我们告诉它这些值必须用df_data['total_open_amount']级数乘以0.7来填充。

使用serie.where将不满足条件的行设置为NaN,所以我们先把series乘以0.7,只留下满足条件的行,也就是带USD的行货币,我们使用 other 参数将其余行保留为初始值

注意series.mask and series.where是相反的

df_data['converted_usd'] = df_data['total_open_amount']\
    .mask(df_data['invoice_currency'] == 'CAD', 
          other=df_data['total_open_amount'].mul(0.7))

或:

df_data['converted_usd'] = df_data['total_open_amount'].mul(0.7)\
    .where(df_data['invoice_currency'] == 'CAD', 
          df_data['total_open_amount'])

numpy 版本

df_data['converted_usd'] = \
np.where(df_data['invoice_currency'] == 'CAD',               
         df_data['total_open_amount'].mul(0.7), 
         df_data['total_open_amount'])