全部,
我有以下长格式数据框:
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 = df['type'].eq('price') & df['asset'].isin(['x', 'y'])
d = df[m].pivot('date', 'asset', 'value').astype(float)
d = pd.concat(
[df, d['x'].sub(d['y']).reset_index(name='value').assign(
asset='x_min_y', type='pricediff')],
ignore_index=True)
详细信息:
创建一个 bool 掩码m
来过滤type
为price
且asset
位于的行>x, y
并使用 DataFrame.pivot
reshape 数据框:
print(d) # pivoted dataframe
asset x y
date
2020-01-01 1.5 1.0
2020-01-02 1.6 1.2
使用 Series.sub
从数据透视数据框中的 y
中减去列 x
,并分配列 asset
和 type
,然后使用 pd.concat
将此旋转数据帧与原始数据帧 df
连接起来。
print(d)
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
关于Python长格式: subtract selection of rows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63114136/