【问题标题】:python, pandas: InvalidIndexError when creating dataframepython,pandas:创建数据框时出现 InvalidIndexError
【发布时间】:2017-10-29 01:04:25
【问题描述】:

我一直在探索titanic dataset。我正在尝试创建一个 dataframe 将在两个单独的列中显示在泰坦尼克号沉没中幸存者和未幸存者的年龄。

    train = pd.read_csv('train.csv')
    test = pd.read_csv('test.csv')    
    whole = pd.concat([train, test])
    df = pd.DataFrame({'survived': whole['Age'][whole['Survived'] == 1],
                       'died': whole['Age'][whole['Survived'] == 0]})

但是我收到了这个错误

pandas.indexes.base.InvalidIndexError: 重新索引仅在以下情况下有效 唯一值索引对象

我做错了什么?

【问题讨论】:

  • 在 pandas 0.20.1 上运行没有错误。
  • 改变这个:whole = pd.concat([train, test])whole = pd.concat([train, test]).reset_index(drop=True)
  • @Nain 是的,它奏效了。你能解释一下是什么问题吗?
  • @ayhan 我使用的是熊猫版本0.19.2 升级到0.20.1 对我不起作用。

标签: python pandas dataframe


【解决方案1】:

在您的代码中进行此更改 whole = pd.concat([train, test]).reset_index(drop=True)

【讨论】:

  • 我们可以改用:pd.concat([train, test], ignore_index=True) ;)
  • @MaxU 这也有效。当您将ignore_index 设置为True 时会发生什么?
  • pd.concat 将为您创建一个新的默认索引 (np.arange(len(concatenated_df))),因此它不需要加入两个现有索引然后再次删除它并创建一个新索引...跨度>
猜你喜欢
  • 2022-12-18
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-13
  • 2021-02-02
  • 2019-03-16
相关资源
最近更新 更多