【发布时间】: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. 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']
【问题讨论】:
-
能不能把DataFrame分享成更容易使用的格式?请参阅:minimal reproducible example。
-
另外,根据数据,可能有更好的方法以表格格式存储。
标签: python python-3.x pandas list dataframe