python - 如何通过匹配两列中的条目来分配新值?
问题描述
我有四列如下所示:
[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,真的不知道是否有简单的方法可以做到这一点......
解决方案
我的方法是合并 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
希望有帮助
推荐阅读
- php - 当我将我的项目上传到在线模式时,在登录 TokenMismatchException Laravel
- java - Android:当 Context 对象不允许 Parcelable 时,我应该如何在活动之间传递 ListView?
- .htaccess - 基于协议限制对目录的访问
- wordpress - 将所有子网址重定向到父页面
- for-loop - 对于表中的行,将行保存在临时表中以在 plpgsql 的选择查询中使用其数据
- azure - Azure 备份 - 文件系统一致、应用程序一致和崩溃一致
- php - 在 laravel 中从 UTC 时区将数据显示到 EST 时区
- r - 将文件名写入列标题
- python - 为什么我不能从 python 的类中导入函数?
- ios - iOS 动态表格视图周围有一个边框