Kan*_*neM 5 python numpy dataframe pandas
我试图对 DataFrame 的两列求和以创建第三列,其中第三列中的值等于其他列的正元素的总和。我尝试了下面的方法,只收到一列 NaN 值
df = pd.DataFrame(np.array([[-1, 2], [-2, 2], [1, -3], [1, -4], [ -2 , -2]]),
columns=['a', 'b'])
df['Sum of Positives'] = 0
df['Sum of Positives'] = df.loc[df.a > 0 ,'a'] +df.loc[df.b >0 , 'b']
Run Code Online (Sandbox Code Playgroud)
数据框:
您可以df.mask在此处使用并填充小于 0 的值,即用 0 填充负值并df.sum在轴 1 上进行处理。
df['sum of pos'] = df.mask(df<0, 0).sum(axis=1)
a b sum of pos
0 -1 2 2
1 -2 2 2
2 1 -3 1
3 1 -4 1
4 -2 -2 0
Run Code Online (Sandbox Code Playgroud)
np.copytot = np.copy(df.values)
np.copyto(t, 0, where=df.values<0)
df['sum of pos'] = t.sum(axis=1)
Run Code Online (Sandbox Code Playgroud)
np.wheredf['sum of pos'] = np.where(df.values<0, 0, df.values).sum(axis=1)
Run Code Online (Sandbox Code Playgroud)
np.clipdf['sum of pos'] = np.clip(df.values, 0, None).sum(axis=1)
Run Code Online (Sandbox Code Playgroud)
np.ma.arraym = np.ma.array(df.values, mask=df.values<0, fill_value=0)
df['sum of pos'] = m.filled().sum(axis=1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
979 次 |
| 最近记录: |