如何将含嵌套列表的多列表数据转换为Pandas DataFrame
解决Python遍历嵌套列表生成Pandas DataFrame的问题
你的代码存在几个语法和逻辑问题:
- 未通过索引关联
Animals、Genders和Properties的对应元素,无法匹配每个动物的属性 - 字典内部不能直接嵌套
for循环,属于语法错误 - 引用未定义的
gender变量,应调用Genders列表中对应位置的值
以下是几种可行的解决方案:
方法一:索引遍历构造字典列表
通过enumerate获取每个动物的索引,精准匹配对应的性别和属性:
import pandas as pd Animals = ['dog', 'cat', 'hamster'] Genders = ['male', 'female', 'male'] Properties = [ ['Brown', '10 Years', 'Sausage', 'Happy'], ['Black', '5 Years', 'Pippin', 'Angry'], ['Yellow', '1 Year', 'Jeff', 'Moody'] ] d = [] for idx, pet in enumerate(Animals): # 按索引取出对应性别和属性 gender = Genders[idx] colour, age, name, sentiment = Properties[idx] d.append({ 'Animal': pet.title(), # 首字母大写与示例格式一致 'Gender': gender.title(), 'Colour': colour, 'Age': age, 'Name': name, 'Sentiment': sentiment }) df = pd.DataFrame(d) print(df)
运行后输出:
Animal Gender Colour Age Name Sentiment 0 Dog Male Brown 10 Years Sausage Happy 1 Cat Female Black 5 Years Pippin Angry 2 Hamster Male Yellow 1 Year Jeff Moody
方法二:直接构造DataFrame列
拆分Properties为单独的列列表,直接传入DataFrame构造函数,更简洁:
import pandas as pd Animals = ['dog', 'cat', 'hamster'] Genders = ['male', 'female', 'male'] Properties = [ ['Brown', '10 Years', 'Sausage', 'Happy'], ['Black', '5 Years', 'Pippin', 'Angry'], ['Yellow', '1 Year', 'Jeff', 'Moody'] ] # 拆分Properties为各列数据 colours = [p[0] for p in Properties] ages = [p[1] for p in Properties] names = [p[2] for p in Properties] sentiments = [p[3] for p in Properties] df = pd.DataFrame({ 'Animal': [a.title() for a in Animals], 'Gender': [g.title() for g in Genders], 'Colour': colours, 'Age': ages, 'Name': names, 'Sentiment': sentiments }) print(df)
方法三:用zip打包数据项
通过zip将所有对应位置的数据打包,直接生成DataFrame:
import pandas as pd Animals = ['dog', 'cat', 'hamster'] Genders = ['male', 'female', 'male'] Properties = [ ['Brown', '10 Years', 'Sausage', 'Happy'], ['Black', '5 Years', 'Pippin', 'Angry'], ['Yellow', '1 Year', 'Jeff', 'Moody'] ] # 打包所有对应字段的数据 data = zip( [a.title() for a in Animals], [g.title() for g in Genders], [p[0] for p in Properties], [p[1] for p in Properties], [p[2] for p in Properties], [p[3] for p in Properties] ) # 指定列名生成DataFrame df = pd.DataFrame(data, columns=['Animal', 'Gender', 'Colour', 'Age', 'Name', 'Sentiment']) print(df)
内容的提问来源于stack exchange,提问作者Curious Student
相关产品推荐
相关产品推荐

