为了账号安全,请及时绑定邮箱和手机立即绑定

在 Pandas 数据框中检查一列并返回另一列

在 Pandas 数据框中检查一列并返回另一列

德玛西亚99 2022-07-26 16:28:35
我有一个这样的数据框:   Title                Participants0  ShowA            B. Smith,C. Ball1  ShowB                   T. Smooth2  ShowC  K. Dulls,L. Allen,B. Smith我,在 Participants 列中拆分并为每个单元格创建一个列表。接下来,我检查每个列表中的特定参与者。在这个例子中,我正在检查B. Smith或者K. Dullsfor item in df['Participants']:    listX = item.split(',')    if 'B. Smith' in listX or 'K. Dulls' in listX:        print(listX)这将返回:['B. Smith', 'C. Ball']['K. Dulls', 'L. Allen', 'B. Smith']1)我猜在我的if声明中有一种更简洁的方法来检查多个参与者。我喜欢任何建议。2)这是我一直在转圈的地方,我如何返回与我返回Title的列表相关联的?在这个例子中,我想返回:ShowAShowC设置代码:import pandas as pddf = pd.DataFrame(data={'Title': ['ShowA', 'ShowB', 'ShowC'],                        'Participants': ['B. Smith,C. Ball', 'T. Smooth', 'K. Dulls,L. Allen,B. Smith']})target_participants = ['B. Smith', 'K. Dulls']
查看完整描述

2 回答

?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

get_dummies

您可以使用pandas.Series.str.get_dummies并创建一个数据框,其中列是名称所在位置的布尔表达式。


dummies = df.Participants.str.get_dummies(',').astype(bool)

dummies


   B. Smith  C. Ball  K. Dulls  L. Allen  T. Smooth

0      True     True     False     False      False

1     False    False     False     False       True

2      True    False      True      True      False

然后我们可以找到你的结果


df.loc[dummies['B. Smith'] | dummies['K. Dulls'], 'Title']


0    ShowA

2    ShowC

Name: Title, dtype: object

contains

否则,您可以使用pandas.Series.str.contains. 首先,我们需要在列表中指定您要查找的人员,然后构造一个字符串以用作正则表达式。


people_to_look_for = ['B. Smith', 'K. Dulls']

pattern = '|'.join(people_to_look_for)

mask = df.Participants.str.contains(pattern)

df.loc[mask, 'Title']


0    ShowA

2    ShowC

Name: Title, dtype: object


查看完整回答
反对 回复 2022-07-26
?
浮云间

TA贡献1829条经验 获得超4个赞

我不确定这样做的性能会有多好,尽管我认为如果您将'Participants'列的元素保留为列表,那么投资是值得的。


import pandas as pd


df = pd.DataFrame(data={'Title': ['ShowA', 'ShowB', 'ShowC'],

                        'Participants': ['B. Smith,C. Ball', 'T. Smooth', 'K. Dulls,L. Allen,B. Smith']})


target_participants = {'B. Smith', 'K. Dulls'}


df['Participants'] = df['Participants'].str.split(',')


print(df, end='\n\n')


contains_parts = ~df['Participants'].map(target_participants.isdisjoint)


print(contains_parts)

输出:


   Title                    Participants

0  ShowA             [B. Smith, C. Ball]

1  ShowB                     [T. Smooth]

2  ShowC  [K. Dulls, L. Allen, B. Smith]


0     True

1    False

2     True

Name: Participants, dtype: bool


查看完整回答
反对 回复 2022-07-26
  • 2 回答
  • 0 关注
  • 201 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号