简体   繁体   English

Pandas 元数据属性未传递给 Groupby 的组 Object

[英]Pandas Metadata Properties Not Passed to Groups of a Groupby Object

Suppose I have假设我有

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)

The print function will throw an AttributeError . print function 将抛出AttributeError

Now, I would need to somehow pass the metadata to each individual group.现在,我需要以某种方式将元数据传递给每个单独的组。 How can this be done?如何才能做到这一点?

You should use this notation ( df['COLNAME'] = 'VALUE' ) to add new columns:您应该使用此表示法 ( 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)

Output: Output:

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

You could still access it from df , no?您仍然可以从df访问它,不是吗?

# ...
for id, group in groups:
    print(df.name)

You could also then assign to each group if you need to do that for whatever reason:如果出于任何原因需要这样做,您也可以分配给每个组:

# ...
for id, group in groups:
    group.name = df.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM