【问题标题】:Why is the largest index is so much lower than the number of rows? [duplicate]为什么最大索引比行数低这么多? [复制]
【发布时间】:2019-12-16 15:11:16
【问题描述】:

我正在学习以下教程,其中的 excel 文件由 3 张具有相同数据结构的工作表组成。当使用 pandas.concat() 将所有工作表放在一起时,我观察到创建的数据框中的行数不同,并且比最后一个索引大得多。

https://www.dataquest.io/blog/excel-and-pandas/

我使用 pandas.shape 来显示行数,并使用 pandas.tail() 从末尾打印 5 行。 代码如下:

import pandas as pd


excel_file = "movies.xls"

xlsx = pd.ExcelFile(excel_file)

movies_sheets = []
for sheet in xlsx.sheet_names:
    movies_sheets.append(xlsx.parse(sheet))

[enter image description here][1]movies = pd.concat(movies_sheets)

print(movies.shape)
print(movies.tail())

这是输出:

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    因为如果使用:

    movies = pd.concat(movies_sheets)
    

    它不创建默认索引,只为每个工作表名连接所有 3 个索引值。

    为了防止它添加ignore_index=True参数到concat

    movies = pd.concat(movies_sheets, ignore_index=True)
    

    或者创建默认索引:

    movies = pd.concat(movies_sheets).reset_index(drop=True)
    

    【讨论】:

      猜你喜欢
      • 2015-06-12
      • 1970-01-01
      • 2014-04-11
      • 2017-08-28
      • 1970-01-01
      • 2010-10-06
      • 2023-04-08
      • 2019-02-18
      • 1970-01-01
      相关资源
      最近更新 更多