首页 > 解决方案 > 在报告中的 Pandas 打印 info() 条目和索引号不一样

问题描述

在 Jupyter notebook I Printed df.info() 结果是

print(df.info())   

<class 'pandas.core.frame.DataFrame'>
Int64Index: 20620 entries, 0 to 24867
Data columns (total 3 columns):
neighborhood    20620 non-null object
bedrooms        20620 non-null float64
price           20620 non-null float64
dtypes: float64(2), object(1)
memory usage: 644.4+ KB

为什么它显示从 0 到 24867 的 20620 个条目?最后一个数字 (24867) 应该是 20620 或 20619

标签: python-3.xpandasjupyter-notebook

解决方案


这意味着并非所有可能的索引值都已被使用。例如,

In [13]: df = pd.DataFrame([10,20], index=[0,100])

In [14]: df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 100
Data columns (total 1 columns):
0    2 non-null int64
dtypes: int64(1)
memory usage: 32.0 bytes

df有 2 个条目,但 Int64Index “范围”从 0 到 100。

df如果行已被删除,或者如果是另一个 DataFrame 的子 DataFrame,DataFrame 很容易像这样结束。

如果您重置索引,索引标签将按顺序重新编号,从 0 开始:

In [17]: df.reset_index(drop=True)
Out[17]: 
    0
0  10
1  20

In [18]: df.reset_index(drop=True).info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 1 columns):
0    2 non-null int64
dtypes: int64(1)
memory usage: 96.0 bytes

更准确地说,正如克里斯指出的那样,这条线

Int64Index: 2 entries, 0 to 100

只是报告 Int64Index 中的第一个和最后一个值。它不报告最小值或最大值。索引中可以有更高或更低的整数:

In [32]: pd.DataFrame([10,20,30], index=[50,0,50]).info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3 entries, 50 to 50  # notice index value 0 is not mentioned
Data columns (total 1 columns):
0    3 non-null int64
dtypes: int64(1)
memory usage: 48.0 bytes

推荐阅读