创建新列并根据python中的其他内容填充它们

时间:2020-04-28 10:45:30

标签: python pandas

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    +

这是一个想法,对于每一行,如果符号为-,则执行:

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

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

您需要分别处理每列,例如将Series.eqnumpy.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

答案 1 :(得分:1)

如果您的数据框不太大,可以尝试一下。

def new_col2(row):
  if row['Sign'] == '-':
    return row['Len'] - row['Çol2']
  return row['Col2']

def new_col3(row):
  if row['Sign'] == '-':
    return row['Len'] - row['Çol3']
  return row['Col3']

df['NewCol2'] = df.apply(new_col2, axis=1)
df['NewCol3'] = df.apply(new_col3, axis=1)