如何汇总熊猫列的特定行

时间:2019-06-19 04:21:30

标签: python pandas

我有以下数据:

    W   X   Y   Z   Pnl
A   1   0   0   0   25    
B   1   1   0   0   34    
C   1   0   0   0   -15    
D   0   0   0   1   2    
E   0   1   0   0   88    
F   1   0   0   0   -46

我想要以下输出:

W   -2  # =25+34-15-46
X   122    
Y   0    
Z   2

3 个答案:

答案 0 :(得分:4)

使用DataFrame.pop提取列,因此所有列可能乘以DataFrame.mul的所有列({{1}被Pnl删除),最后每行的总和是DataFrame.sum

pop

答案 1 :(得分:3)

通过在前4列上执行广播乘法来解决此问题,然后对行求和:

df.iloc[:,:-1].mul(df['Pnl'], axis=0).sum()

W     -2
X    122
Y      0
Z      2
dtype: int64

在哪里

df.iloc[:,:-1].mul(df['Pnl'], axis=0)

    W   X  Y  Z
A  25   0  0  0
B  34  34  0  0
C -15   0  0  0
D   0   0  0  2
E   0  88  0  0
F -46   0  0  0

您还可以使用df.mul(df.pop('Pnl'), axis=0).sum(),但要注意 pop会破坏性地修改df ,避免需要保留输入。


如果性能很重要,请使用numpy

# <0.24 versions 
(df.pop('Pnl').values[:,None] * df.values).sum(axis=0)
# v0.24 onwards
(df.pop('Pnl').to_numpy()[:,None] * df.to_numpy()).sum(axis=0)
# array([ -2, 122,   0,   2])

pd.Series((df.pop('Pnl').to_numpy()[:,None] * df.to_numpy()).sum(axis=0),
          index=df.columns)

W     -2
X    122
Y      0
Z      2
dtype: int64

答案 2 :(得分:0)

  const markerColumn = marker.children.getIndex(0);

  // Optionally straighten out the square
  markerColumn.cornerRadius(0, 0, 0, 0);
  // Hide the square
  markerColumn.defaultState.properties.fillOpacity = 0;
  // Form the bounding box
  markerColumn.defaultState.properties.strokeWidth = 1;
  markerColumn.defaultState.properties.stroke = am4core.color("#000");
  markerColumn.defaultState.properties.strokeOpacity = 1;

  // After your checkbox code... again, omit/comment out the href adapter
  checkbox.href = "https://cdn.onlinewebfonts.com/svg/img_207414.png";
  checkbox.dx = 1;
  checkbox.dy = 1;

  const checkboxActiveState = checkbox.states.create("active");
  checkboxActiveState.properties.opacity = 0;

输出:

time alembic upgrade head