【问题标题】:Pandas reset index after operations on rowsPandas 在对行进行操作后重置索引
【发布时间】:2020-01-12 22:50:32
【问题描述】:

我想知道是否有一种方法可以将新的 .loc 值分配给数据框以便索引该行。 我正在编写通过 .loc[] 为行编制索引的代码,但现在我已将数据帧随机分成两组,因此当我通过 .loc[] 为行编制索引时,我得到一个关键错误,因为该行可能在另一个数据集中。

我希望能够在洗牌后立即为数据分配一个新的 .loc[] 索引,这样我仍然可以像往常一样进行索引。

例如,我有一个数据框:

          length    height...                  water      type
    4     15.85  14.7240  ...               0.173     orange
    92    20.06  17.3565  ...               0.171     orange
    155   22.71  15.8040  ...               0.169     apple
    142   11.76  12.2355  ...               0.175     pear
    91    20.33  16.0785  ...               0.175      apple

给定的索引显示在左侧(即 4 到 91),我想将这些索引值更改为我想要分配的值,即按顺序排列(即 0 到 4)。这样当我调用 .loc[0] 时,它会返回第一行并且不会给我 KeyError,因为该行在另一个数据集中

谢谢。

【问题讨论】:

  • 也许是DataFrame.reindex?尽管这实际上取决于您需要对不存在的行做什么。无论索引是否存在,您都应该可以Set with Enlargment
  • @ALollz 我已经更新了问题以提供一个示例,我不确定 reindex 是否有效
  • 好的,我明白了。你想要df = df.reset_index(drop=True)
  • 非常感谢@ALollz,这对我有用

标签: python pandas dataframe


【解决方案1】:

来自 Pandas 文档:

>>> df = pd.DataFrame([('bird', 389.0),
...                    ('bird', 24.0),
...                    ('mammal', 80.5),
...                    ('mammal', np.nan)],
...                   index=['falcon', 'parrot', 'lion', 'monkey'],
...                   columns=('class', 'max_speed'))
>>> df
         class  max_speed
falcon    bird      389.0
parrot    bird       24.0
lion    mammal       80.5
monkey  mammal        NaN

将 reset_index 与 drop 参数一起使用:

>>> df.reset_index(drop=True)
    class  max_speed
0    bird      389.0
1    bird       24.0
2  mammal       80.5
3  mammal        NaN

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-01
    • 2021-06-10
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2015-11-04
    相关资源
    最近更新 更多