pandas Python:未正确调用 DataFrame 构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29345093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:08:00  来源:igfitidea点击:

Python: DataFrame constructor not properly called

pythonpandasdataframe

提问by Indole

So im walking thourhg the pandas manual and I dont understand what im doing wrong. Could somebody please help? I mean this is standard code from the manual, except that I use a different random function I believe.

所以我正在阅读Pandas手册,我不明白我做错了什么。有人可以帮忙吗?我的意思是这是手册中的标准代码,只是我使用了我认为不同的随机函数。

http://pandas.pydata.org/pandas-docs/dev/advanced.html--> sample window #3

http://pandas.pydata.org/pandas-docs/dev/advanced.html-->示例窗口 #3

import numpy as np
from pandas import DataFrame
import random

arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
         np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]

df = DataFrame(random.random(), index=arrays)

print(df)

>>>DataFrame constructor not properly called!<<<

回答by Padraic Cunningham

pandas is using np.random.randnwhich returns an array. You are passing a single float value using random.random():

pandas 正在使用np.random.randn它返回一个数组。您正在使用random.random()以下方法传递单个浮点值:

In [49]: import numpy as np
In [50]: randn = np.random.randn
In [51]: randn(8)
Out[51]: 
array([ 1.5530158 , -0.08940148,  0.10467891, -0.05558743, -0.90833863,
       -1.05916262,  0.02431885, -2.08940353])    
In [52]: from random import random    
In [53]: random()
Out[53]: 0.697960149473455

If you look at the Dataframe documentation you see what can be passed as data:

如果您查看 Dataframe 文档,您会看到可以作为数据传递的内容:

Parameters :
data : numpy ndarray (structured or homogeneous), dict, or DataFrame Dict can contain Series, arrays, constants, or list-like objects

参数:
数据:numpy ndarray(结构化或同类)、dict 或 DataFrame 字典可以包含系列、数组、常量或类似列表的对象