我有这样一个数据帧:
Title Participants
0 ShowA B. Smith,C. Ball
1 ShowB T. Smooth
2 ShowC K. Dulls,L. Allen,B. Smith
我正在参与者列中的,
上进行拆分,并为每个单元格创建一个列表。接下来,我检查每个列表中的特定参与者。在本例中,我正在检查B. Smith
或K. 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']
get_dummies
您可以使用
pandas.Series.str.get_dummies
并创建一个数据框架,其中列是存在名称的布尔表达式然后我们可以找到你的结果
contains
否则,您可以使用
pandas.Series.str.contains
。首先,我们需要在列表中指定要查找的人,然后构造一个字符串用作正则表达式我不确定这方面的性能会有多好,尽管我认为如果您将
'Participants'
列的元素保留为列表,那么投资是值得的输出:
相关问题 更多 >
编程相关推荐