添加具有不同索引的列会导致 NaN

adding columns with different indicies results in NaN

我的 df:

   df = pd.DataFrame({'p1_profit': {0: -196.50000000000023,
      1: -593.73000000000025,
      2: -712.46000000000026,
      3: -657.88000000000011,
      4: -763.18000000000029},
     'p2_profit': {0: -634.36999999999989,
      1: -737.14999999999998,
      2:  224.41999999999985,
      3: -697.20000000000005,
      4: -526.78999999999996},
     'p3_profit': {0: 211.32999999999981,
      1: -155.02000000000021,
      2: 443.90999999999985,
      3: -75.320000000000164,
      4: 276.24999999999989}})

我想将盈利年份的数量加起来,其中 p1_profit 代表年份 1 的利润,依此类推,每行的列。

我尝试做类似的事情:

np.sign(df[df.p1_profit > 0].p1_profit) + \
np.sign(df[df.p2_profit > 0].p2_profit) + \
np.sign(df[df.p3_profit > 0].p3_profit)

结果:

0   NaN
2   NaN
4   NaN
dtype: float64

问题是每个 np.sign(X) 的结果都有自己的索引,可能与其他调用 np.sign(X) 的结果不同。

期望的结果应该是 row 01 年盈利,row 10- 年盈利等等。

row 0: 1
row 1: 0
row 2: 2
row 3: 0
row 4: 1

对布尔结果使用 sum

In [7]: (df > 0).sum(axis=1)
Out[7]:
0    1
1    0
2    2
3    0
4    1
dtype: int64