【问题标题】:DataFrame slicing and default indexDataFrame 切片和默认索引
【发布时间】:2016-04-12 01:22:21
【问题描述】:

我有一个 pandas.DataFrame df,如下所示。第一列是自动生成的索引。

In[221]: df
Out[220]: 
    name  age sex        job
0   John   15   M    Student
1   Mike   30   M      Labor
2   Lily   41   F    Student
3   Dave   66   M      Labor
4    Sam   23   F  Scientist
5   Luke    7   M      Labor
6  Ellen   80   F      Labor
7  Jacob   52   M      Actor

现在切片后,默认索引被继承。

In[225]: df_labor = df[df.job == 'Labor']
In[226]: df_labor
Out[225]: 
    name  age sex    job
1   Mike   30   M  Labor
3   Dave   66   M  Labor
5   Luke    7   M  Labor
6  Ellen   80   F  Labor

因为自动生成的索引对我来说毫无意义。如何使它们 [0, 1, 2, 3] 而不是 [1, 3, 5, 6],这样当我尝试使用 df_labor.ix[3][' 获取 df_labor 的第三(从零开始)行时name'],我可以得到 'Ellen' 而不是 'Dave'?

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    您需要拨打reset_index:

    df_labor = df[df.job == "Labor"].reset_index(drop = True)
    In [94]: df_labor               
    Out[94]:                
    
        age job     name    sex
    0   30  Labor   Mike    M
    1   66  Labor   Dave    M
    2   7   Labor   Luke    M
    3   80  Labor   Ellen   F
    

    默认情况下,pandas 将旧索引作为列添加到新数据帧中。 drop = True 删除该列。

    【讨论】:

      猜你喜欢
      • 2012-09-13
      • 2018-02-28
      • 1970-01-01
      • 2017-01-15
      • 2020-07-31
      • 2014-12-24
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      相关资源
      最近更新 更多