You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用ColumnsValue引用列名实现DataFrame USD金额计算?

问题描述

现有如下DataFrame:

df
          asset      quantity      eurusd_close     usdtusd_close     btcusd_close    xusd_close
datetime     
2018-01-25   eur         5000          1,123         xxx.         xxx.          xxx.
2018-02-12   btc         0,05          xxx.          xxx.         17542         xxx.
2018-02-15   usdt        15000         xxx.          1,001        xxx.          xxx.
2018-09-26   eur         2500          1,321         xxx.         xxx.          xxx.

需要新增列usd,将quantity列的值按asset列匹配对应的xxxusd_close列(如asset为eur则用eurusd_close)转换为USD金额。尝试以下代码未成功:

df['usd'] = df['quantity'] * df[f'{df.asset.value}usd_close']

同时df.lookup()也未实现需求,求可行解法。


解决方案

前置处理:转换数值格式

注意到quantity和各xxxusd_close列中存在逗号(作为小数分隔符)和xxx.占位符,需先清理并转换为数值类型:

import numpy as np

# 处理quantity列
df['quantity'] = df['quantity'].str.replace(',', '.').astype(float)

# 处理所有usd_close列
close_cols = [col for col in df.columns if 'usd_close' in col]
for col in close_cols:
    df[col] = df[col].str.replace(',', '.').replace('xxx.', np.nan).astype(float)

方法一:逐行匹配计算(apply)

通过apply遍历每一行,根据asset值匹配对应close列后计算:

def calc_usd(row):
    target_col = f"{row['asset']}usd_close"
    return row['quantity'] * row[target_col] if target_col in df.columns else np.nan

df['usd'] = df.apply(calc_usd, axis=1)

方法二:正确使用df.lookup

构造每行对应的close列名数组,结合lookup批量匹配计算:

# 生成每行对应的目标close列名
target_cols = df['asset'] + 'usd_close'
# 过滤无效列名,避免报错
valid_rows = target_cols.isin(df.columns)
df['usd'] = np.where(valid_rows, df.lookup(df.index, target_cols) * df['quantity'], np.nan)

方法三:数据重塑(适合多资产场景)

将宽格式的close列转为长格式,匹配后计算:

# 提取并重塑close列
close_long = df.filter(regex='usd_close').stack().reset_index()
close_long.columns = ['datetime', 'col_name', 'close_price']
close_long['asset'] = close_long['col_name'].str.replace('usd_close', '')

# 合并原数据并计算
df = df.merge(close_long, on=['datetime', 'asset'], how='left')
df['usd'] = df['quantity'] * df['close_price']
# 清理冗余列
df = df.drop(columns=['col_name', 'close_price'])

内容的提问来源于stack exchange,提问作者Wakuu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:41:32