我正在尝试使用存储在单独数据框中的价格更新头寸数据框。我想将最新价格放入“ last_price”列中,并将该价格的数据放入“ last_date”列中。import datetimefrom scipy import statsimport numpy as npimport pandas as pddf_portfolio = pd.DataFrame({ 'amount' : np.random.randint(low=0, high=10, size=(4)), 'timestamp' : pd.Timestamp('20130102'), 'exch' : pd.Categorical(["e1","e1","e2","e2"]), 'token' : pd.Categorical(["BTC","ETH","ETH","LTC"]) })df_ETH_price = pd.DataFrame({ 'date': ('2018-08-11','2018-08-12','2018-08-13'), 'price' : (322.11,319.57,286.50) })df_portfolio['last_price'] = np.nandf_portfolio['last_date'] = "?"print(df_portfolio)print (df_ETH_price)预期结果如下: amount exch timestamp token last_price last_date0 7 e1 2013-01-02 BTC NaN ?1 4 e1 2013-01-02 ETH 286.50 2018-08-132 2 e2 2013-01-02 ETH 286.50 2018-08-133 9 e2 2013-01-02 LTC NaN ?
3 回答
一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
我会在您的价格跟踪数据框中创建一个标记,因此很明显正在谈论哪种代币:
m = df_ETH_price.assign(token='ETH').tail(1)
然后合并:
df_portfolio.merge(
m, how='outer'
).rename(columns={'date': 'last_date', 'price': 'last_price'})
amount timestamp exch token last_date last_price
0 2 2013-01-02 e1 BTC NaN NaN
1 0 2013-01-02 e1 ETH 2018-08-13 286.5
2 3 2013-01-02 e2 ETH 2018-08-13 286.5
3 7 2013-01-02 e2 LTC NaN NaN
添加回答
举报
0/150
提交
取消