全部,
我有以下长格式数据帧:
df = pd.DataFrame({'date': ["2020-01-01","2020-01-01","2020-01-02","2020-01-02","2020-01-01","2020-01-01","2020-01-02","2020-01-02"], 'asset': ["x", "x","x", "x","y","y","y","y"], 'type': ["price", "spread","price","spread","price", "spread","price","spread"], 'value': ["1.5", "0.01","1.6", "0.01","1","0.08","1.2","0.09"]})
看起来是这样的:
date asset type value
0 2020-01-01 x price 1.5
1 2020-01-01 x spread 0.01
2 2020-01-02 x price 1.6
3 2020-01-02 x spread 0.01
4 2020-01-01 y price 1
5 2020-01-01 y spread 0.08
6 2020-01-02 y price 1.2
7 2020-01-02 y spread 0.09
我想从x
的价格中减去y
的价格,并保持相同的数据结构,结果应该如下所示:
date asset type value
0 2020-01-01 x price 1.5
1 2020-01-01 x spread 0.01
2 2020-01-02 x price 1.6
3 2020-01-02 x spread 0.01
4 2020-01-01 y price 1
5 2020-01-01 y spread 0.08
6 2020-01-02 y price 1.2
7 2020-01-02 y spread 0.09
8 2020-01-01 x_min_y pricediff 0.5
9 2020-01-02 x_min_y pricediff 0.4
我想使用pandas的assign()
函数来创建它,但我不确定如何做到这一点
提前谢谢
假设不需要匹配日期,并且数据集的定义如示例所示,则可以执行以下操作:
基本上,执行计算并随后连接
使用:
详细信息:
创建一个布尔掩码} 重新塑造数据帧:
m
以过滤type
为price
且asset
为x, y
的行,并使用^{使用^{} 从数据透视帧中的} 将该数据透视帧与原始数据帧
y
中减去列x
,并分配列asset
和type
,然后使用^{df
连接相关问题 更多 >
编程相关推荐