首页 > 解决方案 > 创建新列并根据 python 中的其他列填充它们

问题描述

ColG Col2 Col3 Len    Sign
G1   1    30   300    +
G2   20   80   200    +
G3   455  720  1000   -
G4   3    40   100    -
G4   2    90   130    +

这是想法,对于每一行,如果 Sign 是-,则执行:

Len-Col2 > NewCol3
Len-Col3 > NewCol2

例子

1000-720=280
1000-455=545
100-40=60
100-3=97

并得到:

ColG Col2 Col3 Len    Sign NewCol2  NewCol3
G1   1    30   300    +    1        30
G2   20   80   200    +    20       80
G3   455  720  1000   -    280      545
G4   3    40   100    -    60       97
G4   2    90   130    +    2        90

谢谢您的帮助

标签: pythonpandas

解决方案


您需要分别处理每一列,例如通过Series.eqwith比较numpy.where

m = df['Sign'].eq('-')

df['NewCol2'] = np.where(m, df['Len'].sub(df['Col3']), df['Col2'])
df['NewCol3'] = np.where(m, df['Len'].sub(df['Col2']), df['Col3'])

或与Series.mask

df['NewCol2'] = df['Col2'].mask(m, df['Len'].sub(df['Col3']))
df['NewCol3'] = df['Col3'].mask(m, df['Len'].sub(df['Col2']))

print (df)
  ColG  Col2  Col3   Len Sign  NewCol2  NewCol3
0   G1     1    30   300    +        1       30
1   G2    20    80   200    +       20       80
2   G3   455   720  1000    -      280      545
3   G4     3    40   100    -       60       97
4   G4     2    90   130    +        2       90

推荐阅读