从具有重复行的两个列表中创建列

2024-10-03 06:30:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在网上查看,我可以看到如何从Pandas中的列表创建列,但是我希望我的列在每个列表的行中具有重复值

示例如下:

students = ['John','Sally','Mike']
tests = ['Math1','CompSci1','English1']

****Desired Outcome from List*****

'Student'    'Test'
 John         Math1
 John         CompSci1
 John         English1
 Sally        Math1
 Sally        CompSci1
 Sally        English1
 Mike         Math1
 Mike         CompSci1
 Mike         English1

谢谢你的帮助


Tags: from示例pandas列表testsjohnlistsally
1条回答
网友
1楼 · 发布于 2024-10-03 06:30:26

一种方法是itertools.product

students = ['John','Sally','Mike']
tests = ['Math1','CompSci1','English1']

from itertools import product

df = pd.DataFrame(product(students,tests), columns=['students','tests'])

输出:

  students     tests
0     John     Math1
1     John  CompSci1
2     John  English1
3    Sally     Math1
4    Sally  CompSci1
5    Sally  English1
6     Mike     Math1
7     Mike  CompSci1
8     Mike  English1

相关问题 更多 >