python-3.x - 用数据框中的属性值替换类对象
问题描述
我有一个包含不同数据类型的数据框,例如这里有两个类 FirstGroup 和 LastGroup。
id1 id2 id3...
0 (0, FirstGroup.Other) (0, FirstGroup.Other) (0, FirstGroup.Static) ...
1 (60, LastGroups.Other) (22, LastGroups.Other) (49, LastGroups.Static) ...
所有这些对象都存储了我想以有效方式提取的数据。一个例子是:df['id1'].[0][1].name
会给我一个字符串变量'type1'
。
我想要这样的东西:
id1 id2 id3...
0 (0, 'type1') (0, 'type1') (0, 'type2') ...
1 (60, 'type1') (22, 'type1') (49, 'type2') ...
我正在寻找与替换方法类似的东西,但除了遍历每一行和每一列外,什么都做不了。
解决方案
您可以使用applymap
:
df.applymap(lambda x: (x[0], x[1].name))
完整示例:
class O:
def __init__(self):
self.name = str(id(self))[-5:]
def __repr__(self):
return 'CustomObject'
df = pd.DataFrame({'id%s' % i: [(j, O()) for j in range(2)] for i in range(3)})
df.applymap(lambda x: (x[0], x[1].name))
输入:
id0 id1 id2
0 (0, CustomObject) (0, CustomObject) (0, CustomObject)
1 (1, CustomObject) (1, CustomObject) (1, CustomObject)
输出:
id0 id1 id2
0 (0, 95984) (0, 98096) (0, 97712)
1 (1, 97328) (1, 98720) (1, 97280)
推荐阅读
- angular - Angular - 如何根据垫选择下拉显示文本/字符串/日期类型
- ios - 在 Swift 中从自定义包中加载颜色资源
- python - 如何根据数组绘制图像?
- android - 全局标志不启动挂起功能?
- javascript - firebase 自定义电子邮件操作处理程序网络
- reactjs - React Ant Design 子菜单菜单项
- string - 删除具有特定字符串值 pandas 的行
- json - 从其 JsValue 字段中按节点排序案例类
- django - 如何让 Django 发送 POST 请求而不是 GET
- jestjs - Jest --changedSince 选项是否也测试相关文件?