DataFrame列表被识别为字符串:无法生成5列12行数据帧问题
解决Pandas构建DataFrame仅显示1行的问题
问题出在你构造数据源字典data的时候——你把每个列表(比如alunos、notas_1_trimestre)都额外套了一层方括号,比如[alunos]。这会让Pandas把整个列表当成单个单元格的值,自然只会生成1行数据。
修正后的代码:
import matplotlib.pyplot as plt import pandas as pd import numpy as np import random nomes = ['João', 'Maria', 'Pedro', 'Pablo', 'Vitor', 'Rogério', 'Marcelo', 'Farias', 'Júlia', 'Diego', 'Rafael', 'Marcos', 'Sofia', 'Kleber', 'David', 'Paulo', 'Rosane', 'Roberta', 'Beatriz', 'Júlio', 'Camile', 'Antônio', 'Otávio'] alunos = random.sample(nomes, 12) notas_1_trimestre = np.random.randint(0,10,12) notas_2_trimestre = np.random.randint(0,10,12) notas_3_trimestre = np.random.randint(0,10,12) notas_4_trimestre = np.random.randint(0,10,12) # 去掉每个值外层的方括号,直接用列表本身 data = { 'Alunos': alunos, 'Notas_1_trimestre': notas_1_trimestre, 'Notas_2_trimestre': notas_2_trimestre, 'Notas_3_trimestre': notas_3_trimestre, 'Notas_4_trimestre': notas_4_trimestre } df = pd.DataFrame(data) print(df) # 可以验证形状是否正确:(12, 5) print(df.shape)
为什么这样能解决?
Pandas构造DataFrame时,字典的每个值需要是可迭代的序列(比如列表、数组),序列里的每个元素对应一行数据。你之前套了外层方括号,相当于把原列表变成了一个包含单个元素(原列表)的新列表,所以Pandas只生成1行,每行的单元格里存的是整个原列表。
内容的提问来源于stack exchange,提问作者Diego Nogueira Rocco
相关产品推荐
相关产品推荐

