Python长格式: subtract selection of rows

标签 python pandas dataframe subtraction

全部,

我有以下长格式数据框:

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来过滤typepriceasset位于的行>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,并分配列 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/

相关文章:

python - 从 Pandas 数据框中的前一行中减去日期时间值

python - 访问 AWS::Lambda::LayerVersion 中定义的自定义 python 模块

python - 返回 Pandas 中组/多索引的前 n 个值

python - 将 DataFrame 列中的唯一值替换为其计数

Pandas 真假匹配

python - Pandas 获取一个数据框中列出的所有行,但不是另一个未排序的行

python - 使用 Pandas 石斑鱼时如何取系列的最大值?

python - 操作系统错误 : [Errno 22] Invalid argument in python3 socket

python - setup.py 没有安装我的 package_data

python - Python 中 sqlite 的 NoSQL 替代方案