首页 > 解决方案 > 熊猫就位在自己身上。变量

问题描述

import pandas as pd

df = pd.DataFrame([[1, 'li'], [2, 'la'], [3, 'lu']], columns=(['index', 'col']))


class Test:
    def __init__(self, data):
        self.data = data
        self.data.set_index('index', inplace = True)


test1 = Test(df)
test2 = Test(df)

print(test1.data)
print(test2.data)

这会引发错误: KeyError: "None of ['index'] are in the columns"

我意识到在方法中使用set_index()with不会操纵属于对象实例的变量。它实际上设置为所有实例共享的类变量。inplace = True__init__self.datadata

当我避免使用时,inplace我没有收到错误,因为现在self.data设置了对象实例的变量。

import pandas as pd

df = pd.DataFrame([[1, 'li'], [2, 'la'], [3, 'lu']], columns=(['index', 'col']))


class Test:
    def __init__(self, data):
        self.data = data
        self.data = self.data.set_index('index', inplace=False)


test1 = Test(df)
test2 = Test(df)

print(test1.data)
print(test2.data)

输出:

       col
index    
1      li
2      la
3      lu
       col
index    
1      li
2      la
3      lu

这种行为的原因是什么?对我来说似乎有点违反直觉,在对以.self

使用 有没有理由或优势inplace = True

标签: pythonpandasdataframe

解决方案


请不要第二次创建 Test 类的对象。一旦你为 test1 对象设置了索引,test2 的数据框中就没有更多的“索引”列了。只需修改与以下相同的代码:

df = pd.DataFrame([[1, 'li'], [2, 'la'], [3, 'lu']], columns=(['index', 'col']))


class Test:
    def __init__(self, data):
        self.data = data
        print(self.data)
        self.data.set_index('index', inplace = True)


test1 = Test(df)
print(test1.data)

推荐阅读