分组依据后,根据另一列创建新的数据框列

时间:2020-02-19 11:31:15

标签: python pandas pandas-groupby

初始数据框:

import pandas as pd
df = pd.DataFrame({'index': [0,0, 1,1, 2,2], 'Name': ['John', 'John', 'Mike', 'Mike', 'Tim', 'Tim'],
                   'Value': ['AAA', 'BBB', 'AAA', 'CCC', 'CCC', 'BBB'], 'Metric':[10, 20, 15,30, 35, 25],
                   'Direction': ['BUY', 'SELL', 'BUY', 'SELL', 'BUY', 'SELL']})

    index Name  Value  Metric Direction
      0  John   AAA      10       BUY
      0  John   BBB      20      SELL
      1  Mike   AAA      15       BUY
      1  Mike   CCC      30      SELL
      2   Tim   CCC      35       BUY
      2   Tim   BBB      25      SELL
  • 新列“ Value_New”

按“索引”分组,创建等于反方向的新列“ Valeu_New”。当direction ==“ BUY”时,“ Value_new”取取Direction ==“ SELL”的值,反之亦然。 对于每个组,就像:

sell_value = df.loc[df.Direction == 'SELL', 'Value'] 
buy_value = df.loc[df.Direction == 'BUY', 'Value']
df.loc[df.Direction == 'BUY', "Value_New"] = sell_value
df.loc[df.Direction == 'SELL', "Value_New"] = buy_value

结果:

index  Name Value  Metric Direction Value_New
  0  John   AAA      10       BUY       BBB
  0  John   BBB      20      SELL       AAA
  1  Mike   AAA      15       BUY       CCC
  1  Mike   CCC      30      SELL       AAA
  2   Tim   CCC      35       BUY       BBB
  2   Tim   BBB      25      SELL       CCC
  • 新列“ Metric_New”

按“索引”分组,创建新列“ Metric_New”,该列等于Direction ==“ SELL”的度量值。忽略“买入”的指标值。对于每个组,就像:

df['Metric_New'] = df.loc[df.Direction == "SELL", 'Metric']

结果:

index  Name Value  Metric Direction  Metric_New
   0  John   AAA      10       BUY          20
   0  John   BBB      20      SELL          20
   1  Mike   AAA      15       BUY          30
   1  Mike   CCC      30      SELL          30
   2   Tim   CCC      35       BUY          25
   2   Tim   BBB      25      SELL          25

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

到目前为止,我发现最好的解决方案是通过索引进行for循环...

for idx in df['index'].unique():
    sell_value = df.loc[(df['index'] == idx) & (df.Direction == 'SELL'), 'Value']
    buy_value = df.loc[(df['index'] == idx) & (df.Direction == 'BUY'), 'Value']
    df.loc[(df['index'] == idx) & (df.Direction == 'SELL'), 'CPBook'] = buy_value.values
    df.loc[(df['index'] == idx) & (df.Direction == 'BUY'), 'CPBook'] = sell_value.values

    sell_metric = df.loc[(df['index'] == idx) & (df.Direction == "SELL"), 'Metric']
    df.loc[(df['index'] == idx),'Metric_New'] = sell_metric.values