加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Dataframe pandas如何将列表作为列传递

发布时间:2020-12-20 12:15:00 所属栏目:Python 来源:网络整理
导读:我有两个列表,例如: list_columns = ['a','b','c','d','e','f','g','h','k','l','m','n'] 和一系列价值观 list_values = [11,22,33,44,55,66,77,88,99,100,111,222] 我想使用list_columns作为列创建Pandas数据帧. 我尝试使用df = pd.DataFrame(list_values,
我有两个列表,例如:

list_columns = ['a','b','c','d','e','f','g','h','k','l','m','n']

和一系列价值观

list_values = [11,22,33,44,55,66,77,88,99,100,111,222]

我想使用list_columns作为列创建Pandas数据帧.

我尝试使用df = pd.DataFrame(list_values,columns = list_columns)
但它不起作用

我收到此错误:ValueError:传递值的形状是(1,12),索引暗示(12,12)

解决方法

数据帧是二维对象.要反映这一点,您需要提供嵌套列表.每个子列表(在本例中是唯一的子列表)表示一行.

df = pd.DataFrame([list_values],columns=list_columns)

print(df)

#     a   b   c   d   e   f   g   h   k    l    m    n
# 0  11  22  33  44  55  66  77  88  99  100  111  222

如果您提供长度大于1的索引,Pandas会为您广播:

df = pd.DataFrame([list_values],columns=list_columns,index=[0,1,2])

print(df)

#     a   b   c   d   e   f   g   h   k    l    m    n
# 0  11  22  33  44  55  66  77  88  99  100  111  222
# 1  11  22  33  44  55  66  77  88  99  100  111  222
# 2  11  22  33  44  55  66  77  88  99  100  111  222

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读