简体   繁体   English

有条件地将一列的值替换为 python 中的另一列

[英]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.

相关问题 有条件地将一个 DataFrame 列中的值替换为另一列中的值 - Conditionally replacing values in one DataFrame column with values from another column 用另一列替换一列但不缺失值 - replacing one column with another column but not missing value 根据另一列包含的单词有条件地为一列赋值 - Conditionally give value to one column based on the words that another column contains 有条件地根据另一列中的值替换值 - Conditionally replacing values based on values in another column 用基于正则表达式的另一个列值替换一个列值 - Python - Replacing a column value by another column value based on regex - Python 如何有条件地(列中的值)在 python 循环中的另一列中搜索子字符串 - how to conditionally (value in column) search for substrings in another column in python loop 有条件地替换列中的值 - conditionally replacing values in a column 用另一个值替换列和行 - replacing column and row with another value Python / Pandas-用另一个数据框中的值替换一个数据框中的元素 - Python/Pandas - Replacing an element in one dataframe with a value from another dataframe 如何在不迭代每一列的情况下有条件地将 dataframe 的一列中的值替换为另一列的值? - How to conditionally replace the value from one column of a dataframe with the value of another without iterating each column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM