[英]Conditionally replacing the value of one column with another in python
This is more or less how one dataframe is:这或多或少是一个 dataframe 的样子:
ID,WinnerID
5863, 13463
4506, 20345
4514, 21012
4543, 20476
I have another file that has some ID's from the ID column that I would like replace with WinnerID我有另一个文件,其中包含 ID 列中的一些 ID,我想将其替换为 WinnerID
Grade ID, etc.
6, 4543, bla bla bla
6, 44519, bla bla bla
6, 44483, bla bla bla
6, 5863, bla bla bla
6, 44532, bla bla bla
6, 5863, bla bla bla
6, 44496, bla bla bla
6, 4543, bla bla bla
I thought of some sort of merge?我想到了某种合并? In sas I would do some logic like
在 sas 我会做一些逻辑,比如
if in1 and not in2 then ID = WinnerID
during a merge but I'm not as familiar with python在合并期间,但我不太熟悉 python
I want the resulting data to be:我希望结果数据是:
Grade ID, etc.
6, 20476, bla bla bla
6, 44519, bla bla bla
6, 44483, bla bla bla
6, 13463, bla bla bla
6, 44532, bla bla bla
6, 13463, bla bla bla
6, 44496, bla bla bla
6, 20476, bla bla bla
I have seen solutions for R, and SQL but nothing for python我已经看到 R 和 SQL 的解决方案,但没有看到 python 的解决方案
Given鉴于
>>> df1
ID WinnerID
0 5863 13463
1 4506 20345
2 4514 21012
3 4543 20476
>>> df2
Grade Date
0 6 4543
1 6 44519
2 6 44483
3 6 5863
4 6 44532
5 6 5863
6 6 44496
7 6 4543
you can use您可以使用
df2['Date'] = df2['Date'].replace(dict(df1.values))
Output: Output:
>>> df2
Grade Date
0 6 20476
1 6 44519
2 6 44483
3 6 13463
4 6 44532
5 6 13463
6 6 44496
7 6 20476
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.