python - New target column based on a pattern
问题描述
Dataframe:
source target
jan feb
mar apr
jun
feb aug
apr jul
oct dec
aug nov
dec may
The output dataframe would be:
source target new_target
jan feb nov
mar apr jul
jun
feb aug nov
apr jul jul
oct dec may
aug nov nov
dec may may
The aim is to create new_target
column based on a logic like - for example, jan
in source has value feb
in target
. This in turn, feb
in source has a value aug
in target
, and so on aug
has nov
in target
column.
So the new_target
column values for jan, feb and aug
will be nov
.
Thanks!
解决方案
首先创建一个用于映射目标的字典,然后将其应用于每个目标
m = dict((zip(df.source, df.target)))
def mapper(x):
for i in range(len(m)):
x = m.get(x, x)
return x
df["new_target"] = df.target.apply(mapper)
推荐阅读
- python - 保存表单时,我需要它保存并在同一页面上继续
- python - 如何在列表理解中的元素之间添加空格?蟒蛇 3
- postman - 第一次如何获取刷新令牌?
- scikit-learn - sklearn-crf 中训练算法的区别
- ios - iOS 实时使用视觉与 ARKit 推理性能下降
- python - Python,在这种情况下用什么代替 itterrows?
- php - PHP 验证检查
- javascript - 没有调用 ComponentDidMount - 非常简单的应用程序
- mysql - 使用 rpm 安装旧版本的 mysql
- android - 如何将小部件从 targetSdkVersion 25 迁移到 26?