簡體   English   中英

Pandas 元數據屬性未傳遞給 Groupby 的組 Object

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

假設我有

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 function 將拋出AttributeError

現在,我需要以某種方式將元數據傳遞給每個單獨的組。 如何才能做到這一點?

您應該使用此表示法 ( 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:

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

您仍然可以從df訪問它,不是嗎?

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

如果出於任何原因需要這樣做,您也可以分配給每個組:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM