python - 创建新列并根据 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
谢谢您的帮助
解决方案
您需要分别处理每一列,例如通过Series.eq
with比较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
推荐阅读
- python - 如何确定语料库中的哪些文本包含由 Python 中的 NLTK 套件生成的错误?
- ios - 在 Swift 中创建 JSON 参数
- node.js - 以不寻常的方式使用 module.exports
- docker - 在 docker-compose 中使用两个主机 IP
- javascript - MSSQL Server 到 PHP 数组到 JSON 编码到 Highcharts
- client - Lazarus json-rpc 客户端
- excel - 从 CSV 文件导入数据错误:名称为 ... 的查询已存在
- python - AttributeError:“模块”对象没有属性“getlogger”
- module - Use module from parent directory in rust
- php - 使用过滤器和选项在 PHP MongoDB 中查询文档的数组字段