gpt4 book ai didi

Python长格式: subtract selection of rows

转载 作者:行者123 更新时间:2023-12-04 09:19:31 28 4
gpt4 key购买 nike

全部,
我有以下长格式数据框:

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
我想减去 y 的价格起价 x并保持相同的数据结构,结果应如下所示:
         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
我想使用 assign() Pandas 的功能来创建这个,但我不知道如何做到这一点。
提前致谢!

最佳答案

使用:

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 所在的行是 priceassetx, 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 减去列 x来自 y在旋转数据框中并分配列 assettype ,然后使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com