【问题标题】:Checking one column and returning another column, in a Pandas Dataframe在 Pandas 数据框中检查一列并返回另一列
【发布时间】:2020-05-27 01:52:06
【问题描述】:

我有一个这样的数据框:

   Title                Participants
0  ShowA            B. Smith,C. Ball
1  ShowB                   T. Smooth
2  ShowC  K. Dulls,L. Allen,B. Smith

我在“参与者”列中拆分,,并为每个单元格创建一个列表。接下来,我检查每个列表中的特定参与者。在此示例中,我正在检查 B. SmithK. Dulls

for 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

在这个例子中,我想返回:

ShowA
ShowC

设置代码:

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']

【问题讨论】:

  • 能不能把DataFrame分享成更容易使用的格式?请参阅:minimal reproducible example
  • 另外,根据数据,可能有更好的方法以表格格式存储。

标签: python python-3.x pandas list dataframe


【解决方案1】:

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

【讨论】:

  • 我喜欢 pandas.Series.str.contains 解决方案,尽管它确实带来了与匹配单词相关的常见烦恼。
  • 您的contains 解决方案完全符合我的要求,谢谢!我对get_dummies 解决方案很感兴趣。是否有一种简单的方法来详细说明它,以便按出现次数列出参与者? (即“B. Smith”将出现 2 次,而其余的将出现 1 次)。
【解决方案2】:

我不确定这样做的性能会有多好,尽管我认为如果您将 '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

【讨论】:

  • 谢谢你,@AMC!我可能会在以后提到这一点。
猜你喜欢
  • 1970-01-01
  • 2017-09-11
  • 2022-11-28
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多