python - 熊猫就位在自己身上。变量
问题描述
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.data
data
当我避免使用时,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
?
解决方案
请不要第二次创建 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)
推荐阅读
- java - 反序列化 JSON 请求中包含许多对象的列表期间的性能问题
- r - conda 创建 R 环境
- python - ValueError:对象类型没有名为 1 的轴
- reactjs - event.target.value 句柄为 ENUM
- wordpress - 切换菜单按钮被链接标签包裹
- mysql - 查找与特定优惠券关联的所有订单
- android - Android:在列表视图中禁用元素上的 scolling
- android - 具有水平对齐和自动调整大小的 ConstraintLayout、TextView 和 ImageView
- python - python中多重继承的调用过程
- apache-spark - 结构化流式多水印