python - Pandas 数据框的切片列在从该列创建的新对象中不断提及原始列名称

标签 python pandas slice

我从 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/

相关文章:

python - 为什么这个 Python ascii 字符串不等于常规字符串?

pointers - 返回给函数的调用者时无法保留 golang 字段的值

python - 大 numpy 数组的加速切片

python - 只读取包含大量列的大型文本数据文件的最后一列

python - 重新排列字典的输出 (Python)

python - 将分类移至生产环境

python - 如何获取列和行来自另一个数据框的列值的数据框?

python - 将pandas中的一列拆分为多列

python - 如何按 Python (pandas) 中列中的出现次数对 Dataframe 进行排序

python - 通过在 Python 中切片列表来分配值的紧凑方法