Python (x,)在NumPy形状中表示什么?
我一直在努力寻找(x,)在NumPy形状中到底表示什么?从外观上看,我知道它说明数组中有“x”个列/元素,基本上是1D数组 但我的问题是,这里(x,)后面的逗号表示什么?我问这个问题是因为,我试图创建一个数据帧,但它给了我一个错误:Python (x,)在NumPy形状中表示什么?,python,arrays,numpy,Python,Arrays,Numpy,我一直在努力寻找(x,)在NumPy形状中到底表示什么?从外观上看,我知道它说明数组中有“x”个列/元素,基本上是1D数组 但我的问题是,这里(x,)后面的逗号表示什么?我问这个问题是因为,我试图创建一个数据帧,但它给了我一个错误: ValueError: Shape of passed values is (3, 1), indices imply (1, 3) 我的代码: price = np.array([10, 8, 12]) df_price = pd.DataFrame(pric
ValueError: Shape of passed values is (3, 1), indices imply (1, 3)
我的代码:
price = np.array([10, 8, 12])
df_price = pd.DataFrame(price,
index=(["Price"]),
columns=(["Almond Butter","Peanut Butter", "Cashew Butter"]))
有人能告诉我为什么这个“价格”数组的形状是(3,1)吗?事实并非如此。它是(3,)--就是这样。当试图从平面阵列创建Pandas数据帧时,该阵列必须转换为某种2D形式,因为Pandas数据帧几乎总是2D的 出现这个问题是因为您有一行三列,所以数据数组的形状应该是
(1,3)
。pd.DataFrame
构造函数必须将维度添加到数组的末尾,并假定第一个维度中的每个项都是DataFrame中的一行
一个简单的修复方法是将数据数组的行数改为列数
price = np.array([10, 8, 12]).reshape(1, -1)
上面的
.reformate
调用中的-1
告诉函数推断该轴的长度。对错误的完整回溯表明DataFrame
对输入进行了大量处理
In [336]: pd.DataFrame(np.arange(1,4),
...: index=(["Price"]),
...: columns=(["Almond Butter","Peanut Butter", "Cashew Butter"]))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/pandas/core/internals/managers.py in create_block_manager_from_blocks(blocks, axes)
1653 blocks = [
-> 1654 make_block(values=blocks[0], placement=slice(0, len(axes[0])))
1655 ]
/usr/local/lib/python3.6/dist-packages/pandas/core/internals/blocks.py in make_block(values, placement, klass, ndim, dtype)
3052
-> 3053 return klass(values, ndim=ndim, placement=placement)
3054
/usr/local/lib/python3.6/dist-packages/pandas/core/internals/blocks.py in __init__(self, values, placement, ndim)
124 raise ValueError(
--> 125 f"Wrong number of items passed {len(self.values)}, "
126 f"placement implies {len(self.mgr_locs)}"
ValueError: Wrong number of items passed 1, placement implies 3
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-336-43d59803fb0f> in <module>
1 pd.DataFrame(np.arange(1,4),
2 index=(["Price"]),
----> 3 columns=(["Almond Butter","Peanut Butter", "Cashew Butter"]))
/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
462 mgr = init_dict({data.name: data}, index, columns, dtype=dtype)
463 else:
--> 464 mgr = init_ndarray(data, index, columns, dtype=dtype, copy=copy)
465
466 # For data is list-like, or Iterable (will consume into list)
/usr/local/lib/python3.6/dist-packages/pandas/core/internals/construction.py in init_ndarray(values, index, columns, dtype, copy)
208 block_values = [values]
209
--> 210 return create_block_manager_from_blocks(block_values, [columns, index])
211
212
/usr/local/lib/python3.6/dist-packages/pandas/core/internals/managers.py in create_block_manager_from_blocks(blocks, axes)
1662 blocks = [getattr(b, "values", b) for b in blocks]
1663 tot_items = sum(b.shape[0] for b in blocks)
-> 1664 construction_error(tot_items, blocks[0].shape[1:], axes, e)
1665
1666
/usr/local/lib/python3.6/dist-packages/pandas/core/internals/managers.py in construction_error(tot_items, block_shape, axes, e)
1692 if block_shape[0] == 0:
1693 raise ValueError("Empty data passed with indices specified.")
-> 1694 raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}")
1695
1696
ValueError: Shape of passed values is (3, 1), indices imply (1, 3)
与(3,1)输入相同:
但是你想要一个(1,3):
numpy
广播可以将(3,)数组扩展到(1,3),但这不是DataFrame
所做的
根据您对它的看法,熊猫数据帧可能看起来是2d numpy数组的转置。序列是一维的,但垂直显示。数据帧索引优先于列。在探索底层数据存储和值/to_numpy()
输出之间的联系时,我也看到了转换。细节很复杂。请注意,回溯讨论了“block_manager”等
In [342]: pd.Series(np.arange(1,4))
Out[342]:
0 1
1 2
2 3
dtype: int64
我的问题是,这里(x,)后面的逗号表示什么
此语法是通用Python,不特定于Numpy。在这种情况下,当我们想要创建一个元组时,我们会添加一个逗号。您应该熟悉元组,如
(3,4)
。但是,如果我们想创建一个只有一个元素的元组呢。您可以尝试(3)
,但现在Python将括号解释为数学表达式中的分组运算符,与我们使用括号时的方式相同,如(3+4)*5
。这意味着(3)
只是整数值3
,而不是元组。因此,我们添加一个逗号(3,)
来创建一个包含单个元素的元组。在通用Python语法中,(3,)
表示一个元组,其中数字3是唯一的元素。@Oso-(3,)
不是(3,1)
的缩写。它们有相同数量的元素,但第一个是1D,第二个是2D。你完全正确,我在考虑另一个库。所以这里的问题是数组被转置了?嗨@jakub,是的,我知道一个是1D,第二个是2D。但我的问题仍然存在。这里(x,)后面的逗号表示什么?因为,我在基于以下错误创建数据帧时遇到了问题:ValueError:传递值的形状是(3,1),索引暗示(1,3)。如果它是一维数组,那么为什么这个错误显示它是二维(3,1)?这是否回答了您的问题?哦,对了。我是否应该考虑并注意到熊猫数据文件总是与2D等阵列一起工作,而不是用1D或0D来工作?数据文件的1D变体是<代码>熊猫。系列< /代码>。您可能可以制作0D系列或数据帧,但它不会有用:)是的,我知道熊猫。实际上是系列。但是我们是从一个Numpy数组构建这个数据帧的。这就是为什么。:-)
In [339]: pd.DataFrame(np.arange(1,4)[:,None]) # (3,1) input
Out[339]:
0
0 1
1 2
2 3
In [340]: pd.DataFrame(np.arange(1,4)[None,:]) # (1,3) input
Out[340]:
0 1 2
0 1 2 3
In [342]: pd.Series(np.arange(1,4))
Out[342]:
0 1
1 2
2 3
dtype: int64