python - 将描述作为属性添加到 Pandas DataFrame 列
问题描述
我想在我的 DataFrame 中添加对每一列的描述作为每列属性。回顾一下 SO 上的内容,大约 8 年前在将我自己的描述属性添加到 Pandas DataFrame时提出了一个类似的问题,但没有答案。最近,在Python Dataframe 添加描述到列中再次提出了这个问题,并收到了使用_metadata
and的答案.attrs
。但是,答案似乎是针对数据框级别的属性,而不是列级别的。使用该方法设置列级属性不会在操作后传播这些属性。例如:
import pandas as pd
class SubclassedDataFrame(pd.DataFrame):
# normal properties
_metadata = ['description']
@property
def _constructor(self):
return SubclassedDataFrame
data = {"a": [1, 2, 3], "b": [10, 12, 13]}
df = SubclassedDataFrame(data)
df.description = "About my data"
df['a'].description = 'column a description'
结果:
df.description # prints 'About my data'
df.head().description # prints 'About my data' after manipulation
df['a'].description # prints 'column a description'
df['a'].head().description # **raises AttributeError**
如何设置在操作后仍然存在的列级属性?如果我遗漏了一些明显的东西,我深表歉意。
解决方案
推荐阅读
- java - 如何使两个字段的条件?
- roslyn - 自最近升级以来新生成的 GeneratedMSBuildEditorConfig 文件
- mongodb - 如何在mongodb中使用多个条件获取左连接数据
- php - 在 Symfony 4.4 中实现自定义错误控制器
- node.js - 如何在猫鼬中更新和删除数组中的项目?
- jsonpath - 使用 JSONPath 从 Web 服务 JSON 响应中提取值
- python - 无法从本地文件夹导入模块?“没有命名模块”
- reactjs - 如何在 React APP 中启用 Azure AD B2C 登录
- python - 如何在pygame的屏幕上拖动一个对象?
- python - 在 numpy 中将 uint32 位转换为浮点数