【问题标题】:How to fix trouble with set_index function in pandas [duplicate]如何解决 Pandas 中 set_index 函数的问题[重复]
【发布时间】:2020-02-23 18:45:21
【问题描述】:

当按照规定的方式在 pandas 中使用 set_index 函数设置索引时,输出中的索引不会改变,因此 loc 函数不会选择标签。我正在使用 Spyder 运行程序。

import pandas as pd
      df = pd.DataFrame({'age':[30, 2, 12, 4, 32, 33, 69],
               'color':['blue', 'green', 'red', 'white', 'gray', 'black', 
      'red'],
               'food':['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 
      'Melon', 'Beans'],
               'height':[165, 70, 120, 80, 180, 172, 150],
               'score':[4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2],
               'state':['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX'],
               'Name':['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean', 
      'Christina', 'Cornelia']})
       df.set_index('color')
       print(df.head(5))

上面是返回以下输出。

  age  color    food  height  score state      Name
0   30   blue   Steak     165    4.6    NY      Jane``
1    2  green    Lamb      70    8.3    TX      Nick
2   12    red   Mango     120    9.0    FL     Aaron
3    4  white   Apple      80    3.3    AL  Penelope
4   32   gray  Cheese     180    1.8    AK      Dean

【问题讨论】:

    标签: pandas


    【解决方案1】:

    正如@ALollz 在他们的回复中所说,您的问题是.set_index 方法的使用。具体来说,使用您拥有它的方式返回一个具有调整索引的数据框,而您希望它直接在您使用该方法的那个上工作。为此,您需要使用inplace=True 参数。

    import pandas as pd
    df = pd.DataFrame({'age':[30, 2, 12, 4, 32, 33, 69],
          'color':['blue', 'green', 'red', 'white', 'gray', 'black', 'red'],
          'food':['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 'Melon', 'Beans'],
          'height':[165, 70, 120, 80, 180, 172, 150],
          'score':[4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2],
          'state':['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX'],
          'Name':['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean', 'Christina', 'Cornelia']})
    df = df.set_index('color')
    # or df.set_index('color', inplace=True)
    print(df.head(5))
    

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 2021-10-14
      • 2022-08-13
      • 2022-01-22
      • 2019-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多