python-3.x - Getting ValueError: DataFrame constructor not properly called while creating a dataframe from lists of list
问题描述
I am getting below error while converting Lists of list to dataframe:
raise ValueError('DataFrame constructor not properly called!') ValueError: DataFrame constructor not properly called!
I have used numpy to split the list and now need to convert those lists of list to a dataframe:
import numpy as np
import pandas as pd
def SplitList():
l = np.array([6,2,5,1,3,6,9,7,6])
n = 3
list = l.reshape((len(l)//n), n).T
print(list)
df = pd.DataFrame(list)
解决方案
首先,不要list
用作变量名,它是 Python 中的保留关键字。
其次,你需要你的函数到return
你的重塑数组,所以你需要:
import numpy as np
import pandas as pd
def SplitList():
l = np.array([6,2,5,1,3,6,9,7,6])
n = 3
a = l.reshape((len(l)//n), n).T
return a
df = pd.DataFrame(SplitList())
print(df)
0 1 2
0 6 1 9
1 2 3 7
2 5 6 6
只是一个建议,但可能是使您的功能更可重用的想法。例如:
def split_list(arr, n):
arr = np.array(arr)
return arr.reshape(-1, n).T
split_list([6,2,5,1,3,6,9,7,6], 3)
[出去]
[[6 1 9]
[2 3 7]
[5 6 6]]
推荐阅读
- c - main vs _start 中的返回值
- javascript - 模态没有出现在点击
- json - 使用json从django后端获取并显示reactjs中的图像
- javascript - 创建纵横比计算器
- c# - 动态更改自定义组合框样式
- javascript - 我的开尔文/华氏转换器的内部 JavaScript 无法正常工作
- r - 如何在闪亮或 flexdahsboard 中制作用户选择的变量图表?
- java - 有没有办法在单独的类文件中从 ActionListener 引用 setVisible() 和 dispose() ?
- javascript - 试图从函数内部 .push 到外部和/或试图让我的函数在 console.log 中吐出一行
- reactjs - React-bootstrap,行和列,如何在移动设备上制作列堆叠?