如何将三个独立元组作为列构建Pandas DataFrame?
问题:多列表构建DataFrame列时触发ValueError
场景复现
现有以下数据列表:
import pandas as pd tuple_1 = [1,2,3,4,5] tuple_2 = ['a', 'b', 'c', 'd', 'e'] tuple_3 = [10,20,30,40,50]
单独用一个列表构建DataFrame列时正常运行:
df = pd.DataFrame(data=tuple_1, columns=['Tuple 1']) print(df)
输出:
Tuple 1 0 1 1 2 2 3 3 4 4 5
但尝试用三个列表构建多列时出现错误:
df = pd.DataFrame(data=[tuple_1, tuple_2, tuple_3], columns=['Tuple 1', 'Tuple 2', 'Tuple 3'])
报错信息:
ValueError: 3 columns passed, passed data had 5 columns
期望输出:
Tuple 1 Tuple 2 Tuple 3 0 1 a 10 1 2 b 20 2 3 c 30 3 4 d 40 4 5 e 50
错误原因
当你把三个列表嵌套传入data参数时,pandas会将每个子列表识别为一行数据,此时传入的数据是3行、5列的结构,但你指定了3列,列数不匹配,因此触发报错。
解决方法
方法1:使用字典传入(推荐)
直接用字典映射列名与对应数据列表,pandas会自动将每个字典值作为一列:
import pandas as pd tuple_1 = [1,2,3,4,5] tuple_2 = ['a', 'b', 'c', 'd', 'e'] tuple_3 = [10,20,30,40,50] df = pd.DataFrame({ 'Tuple 1': tuple_1, 'Tuple 2': tuple_2, 'Tuple 3': tuple_3 }) print(df)
方法2:转置数据后指定列名
先将原行格式的数据转置为列格式,再设置对应列名:
import pandas as pd tuple_1 = [1,2,3,4,5] tuple_2 = ['a', 'b', 'c', 'd', 'e'] tuple_3 = [10,20,30,40,50] df = pd.DataFrame(data=[tuple_1, tuple_2, tuple_3]).T df.columns = ['Tuple 1', 'Tuple 2', 'Tuple 3'] print(df)
两种方法均能得到期望的输出结果。
内容的提问来源于stack exchange,提问作者valentim.kodak
相关产品推荐
相关产品推荐

