python教程

当前位置:首页 > Pandas教程 > 当前文章

Pandas教程

pandas坑:创建df后多行数据重复

2021-11-23 186赞 老董笔记

  字典可以创建成df数据结构,但是必须传参index,否则会报错ValueError: If using all scalar values, you must pass an index。如下:

# -*- coding:utf-8 -*-
dic = {'domain': 'www.python66.com', 'author': 'dong',}
df = pd.DataFrame(dic)
print(df)
raise ValueError("If using all scalar values, you must pass an index")
ValueError: If using all scalar values, you must pass an index

  如果传参写成了标量的形式还会报错Index(...) must be called with a collection of some kind, 0 was passed。如下:

# -*- coding:utf-8 -*-
dic = {'domain': 'www.python66.com', 'author': 'dong',}
df = pd.DataFrame(dic,index=0)
print(df)
raise cls._scalar_data_error(data)
TypeError: Index(...) must be called with a collection of some kind, 0 was passed

  如果传参写成了列表的形式则没问题

# -*- coding:utf-8 -*-

dic = {'domain': 'www.python66.com', 'author': 'dong',}
df = pd.DataFrame(dic,index=[0])
print(df)
             domain author
0  www.python66.com   dong

  如果传参的列表不是单个元素而是多个,结果则是重复出现同1行数据,虽然不报错,我觉得这是个坑

# -*- coding:utf-8 -*-

dic = {'domain': 'www.python66.com', 'author': 'dong',}
df = pd.DataFrame(dic,index=[0,1,2])
print(df)
             domain author
0  www.python66.com   dong
1  www.python66.com   dong
2  www.python66.com   dong

感兴趣直接点击图片获取>>

文章评论

pandas坑:创建df后多行数据重复文章写得不错,值得赞赏