Python Pandas基于列值的条件替换字符串 [英] Python pandas conditional replace string based on column values
问题描述
给出这些数据框...:
Given these data frames...:
DF = pd.DataFrame({'COL1': ['A', 'B', 'C', 'D','D','D'],
'COL2': [11032, 1960, 11400, 11355, 8, 7],
'year': ['2016', '2017', '2018', '2019', '2020', '2021']})
DF
COL1 COL2 year
0 A 11032 2016
1 B 1960 2017
2 C 11400 2018
3 D 11355 2019
4 D 8 2020
5 D 7 2021
DF2 = pd.DataFrame({'ColX': ['D'], 'ColY':['2021'], 'ColZ':[100]
DF2
ColX ColY ColZ
0 D 2021 100
如果满足以下条件:
COL1 =来自DF2的ColX
COL1 = ColX from DF2
year = DF2的ColY
year = ColY from DF2
然后将COL2中的值从DF2更改为ColZ.
Then change the value in COL2 to ColZ from DF2.
推荐答案
这似乎是您想update
DF
使用来自DF2
的数据.
This looks like you want to update
DF
with data from DF2
.
假定DF2
中的所有值对于ColX
和ColY
中的给定值对都是唯一的:
Assuming that all values in DF2
are unique for a given pair of values in ColX
and ColY
:
DF = DF.merge(DF2.set_index(['ColX', 'ColY'])[['ColZ']],
how='left',
left_on=['COL1', 'year'],
right_index=True)
DF.COL2.update(DF.ColZ)
del DF['ColZ']
>>> DF
COL1 COL2 year
0 A 11032 2016
1 B 1960 2017
2 C 11400 2018
3 D 11355 2019
4 D 8 2020
5 D 100 2021
我将一个临时数据帧(DF2.set_index(['ColX', 'ColY'])[['ColZ']]
)合并到DF中,这将添加来自ColZ的所有值,其中其索引(ColX
和ColY
)的索引与DF
中的COL1
和year
的值匹配.所有不匹配的值都用NA
填充.
I merge a temporary dataframe (DF2.set_index(['ColX', 'ColY'])[['ColZ']]
) into DF, which adds all the values from ColZ where its index (ColX
and ColY
) match the values from COL1
and year
in DF
. All non-matching values are filled with NA
.
然后我使用update
从DF.ColZ中的非空值覆盖DF.COL2
中的值.
I then use update
to overwrite the values in DF.COL2
from the non-null values in DF.ColZ.
然后我删除DF ['ColZ']进行清理.
I then delete DF['ColZ'] to clean-up.
如果ColZ
与DF
中的现有列名称匹配,则需要进行一些调整.
If ColZ
matches an existing column name in DF
, then you would need to make some adjustments.
替代解决方案如下:
DF = DF.set_index(['COL1', 'year']).update(DF2.set_index(['ColX', 'ColY']))
DF.reset_index(inplace=True)
输出与上面的输出相同.
The output is identical to that above.
这篇关于Python Pandas基于列值的条件替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!