首页 > 解决方案 > 将描述作为属性添加到 Pandas DataFrame 列

问题描述

我想在我的 DataFrame 中添加对每一列的描述作为每列属性。回顾一下 SO 上的内容,大约 8 年前在将我自己的描述属性添加到 Pandas DataFrame时提出了一个类似的问题,但没有答案。最近,在Python Dataframe 添加描述到列中再次提出了这个问题,并收到了使用_metadataand的答案.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**

如何设置在操作后仍然存在的列级属性?如果我遗漏了一些明显的东西,我深表歉意。

标签: pythonpandasdataframeattributesmetadata

解决方案


推荐阅读