首页 > 解决方案 > 如何通过匹配两列中的条目来分配新值?

问题描述

我有四列如下所示:

[Case Number] [Party Type] [Party Name] [Attorney For]
01             Plaintiff        A            nan
01             Plaintiff        B            nan
01             Defendant        C            nan
01             Attorney         D            A
01             Attorney         E            C
02  ...
03  ...

在每个案例中,如何替换律师的当事人类型以反映他/她为之工作的当事人?

例如,人 D 是 的代理人Plaintiff A,所以我想将他的当事人类型更改为Plaintiff Attorney

也就是说,我希望数据集看起来像:

[Case Number]   [Party Type]         [Party Name] [Attorney For]
01              Plaintiff               A            nan
01              Plaintiff               B            nan
01              Defendant               C            nan
01              PlaintiffAttorney       D            A
01              DefendantAttorney       E            C
02   ...
03   ...

我刚开始学习python,真的不知道是否有简单的方法可以做到这一点......

标签: pythonpython-3.x

解决方案


我的方法是合并 DataFrame 本身(您只需要列的一个子集:合并列和PartyType),将Attorney for-column 与Party Name. 完成后,您只需查找该列的 Party 类型,并将其添加到 string "Attorney"

df_2 = df.merge(df[['[CaseNumber]', '[PartyName]', '[PartyType]']], 
                how='left', left_on=['[CaseNumber]', '[AttorneyFor]'],
                right_on=['[CaseNumber]', '[PartyName]'], suffixes=('', '_y'))
# suffixes to specify we don't want to rename the original columns
# Add the strings together if it's an attorney, otherwise pick original Party Type
df_2['New Party Type'] = np.where(df_2['[PartyType]_y'].notnull(),
                                        df_2['[PartyType]_y'] + df_2['[PartyType]'],
                                        df_2['[PartyType]'])
# Drop merge columns
df_2.drop(columns=['[PartyName]_y', '[PartyType]_y'])

#Output:
#       [CaseNumber] [PartyType] [PartyName] [AttorneyFor]     New Party Type
#0             1   Plaintiff           A           NaN          Plaintiff
#1             1   Plaintiff           B           NaN          Plaintiff
#2             1   Defendant           C           NaN          Defendant
#3             1    Attorney           D             A  PlaintiffAttorney
#4             1    Attorney           E             C  DefendantAttorney

希望有帮助


推荐阅读