首页 > 解决方案 > Pandas 元数据属性未传递给 Groupby 对象的组

问题描述

假设我有

df = pd.DataFrame({'A': [1,2,3], 'B': [1,2,1]})
df._metadata += "name"
df.name = "The Name"

groups = df.groupby(by="B")
for id, group in groups:
    print(group.name)

print函数将抛出一个AttributeError.

现在,我需要以某种方式将元数据传递给每个单独的组。如何才能做到这一点?

标签: pythonpandas

解决方案


您应该使用此表示法 ( df['COLNAME'] = 'VALUE') 添加新列:

df = pd.DataFrame({'A': [1,2,3], 'B': [1,2,1]})
df['_metadata'] = "name"
df['name'] = "The Name"

groups = df.groupby(by="B")
for id, group in groups:
    print(group.name)

输出:

0    The Name
2    The Name
Name: name, dtype: object
1    The Name
Name: name, dtype: object

推荐阅读