Python 如何映射其他两个匹配的列值&引用;仅对唯一值的索引对象“重新编制索引”有效;?

Python 如何映射其他两个匹配的列值&引用;仅对唯一值的索引对象“重新编制索引”有效;?,python,dataframe,Python,Dataframe,我有一个数据帧df,我有四列,如下所示: IDP1 IDP1Number IDP2 IDP2Number 1 100 1 NaN 3 110 2 150 5 120 3 NaN 7 140 4 160 9 150 5 190 NaN NaN

我有一个数据帧df,我有四列,如下所示:

IDP1    IDP1Number    IDP2    IDP2Number
1       100           1       NaN
3       110           2       150
5       120           3       NaN
7       140           4       160
9       150           5       190
NaN     NaN           6       130
NaN     NaN           7       NaN
NaN     NaN           8       200
NaN     NaN           9       90
NaN     NaN           10      NaN
相反,我想使用IDP1到IDP2将值从df.IDP1Number映射到IDP2Number。如果IDP1和IDP2都存在IDP1Number,我想替换现有值。否则,只保留IDP2Number中的值

The error message that appears reads, " Reindexing only valid with uniquely value Index objects
下面的数据框是我想要的:

IDP1    IDP1Number    IDP2    IDP2Number
1       100           1       100
3       110           2       150
5       120           3       110
7       140           4       160
9       150           5       120
NaN     NaN           6       130
NaN     NaN           7       140
NaN     NaN           8       200
NaN     NaN           9       150
NaN     NaN           10      NaN
以下是一种方法:

# filter the data and create a mapping dict
maps = df.query("IDP1.notna()")[['IDP1', 'IDP1Number']].set_index('IDP1')['IDP1Number'].to_dict()

# create new column using ifelse condition
df['IDP2Number'] = df.apply(lambda x: maps.get(x['IDP2'], None) if (pd.isna(x['IDP2Number']) or x['IDP2'] in maps) else x['IDP2Number'], axis=1)

print(df)

   IDP1  IDP1Number  IDP2  IDP2Number
0   1.0       100.0     1       100.0
1   3.0       110.0     2       150.0
2   5.0       120.0     3       110.0
3   7.0       140.0     4       160.0
4   9.0       150.0     5       120.0
5   NaN         NaN     6       130.0
6   NaN         NaN     7       140.0
7   NaN         NaN     8       200.0
8   NaN         NaN     9       150.0
9   NaN         NaN    10         NaN

非常感谢,直观地说,这里发生了什么?我们创建了一个dict,它将
IDP1
映射到
IDP1Number
值。然后,使用ifelse检查,如果
IDP2Number
中的值为
NA
,则使用
IDP2
中相应的值替换为dict中的值。你应该在每一步之后打印结果,以获得视觉效果。可以,这是有意义的。它还解决了索引大小不同的问题,这非常有帮助!