我从 pandas 数据帧中切片来创建对象标签。原始数据框中的列名称为y
。
现在,当我获取 label
的总和并将其分配给 m
时,在打印时它不断显示 y
。为什么要这样做?它试图通过编写 y 50.0
来表达什么意思?
>>> type(label)
<class 'pandas.core.frame.DataFrame'>
>>> label.head(2)
y
0 1.0
1 1.0
>>> m = label.sum()
>>> m
y 50.0
dtype: float64
>>>
最佳答案
您的label
DataFrame 仅包含 1 个名为 y
的列有 50 行 1.0
,所以它返回 sum of y
。在您的代码中,该名称成为索引名称(单列的总和),因为 DataFrame 中的所有索引都需要一个名称,您可以使用 m.index = <insert a name or int here>
重命名它。 ,但是m.index = None
将提高TypeError
异常。
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.ones(50), columns=['y'])
>>> df.head(2)
y
0 1.0
1 1.0
>>> df
y
0 1.0
1 1.0
2 1.0
3 1.0
4 1.0
... # reducted
48 1.0
49 1.0
>>> df.sum()
y 50.0
dtype: float64
>>> m = df.sum()
>>> m
y 50.0
dtype: float64
>>> m.index
Index(['y'], dtype='object')
>>> m.index = None
Traceback (most recent call last):
...
TypeError: Index(...) must be called with a collection of some kind, None was passed
关于python - Pandas 数据框的切片列在从该列创建的新对象中不断提及原始列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52685466/