python - 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
.
现在,我需要以某种方式将元数据传递给每个单独的组。如何才能做到这一点?
解决方案
您应该使用此表示法 ( 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
推荐阅读
- flutter - 检查表是否存在于颤动中
- next.js - 在 NextJS 教程中,什么被视为单个“请求”?
- python - AssertionError:视图函数映射正在覆盖现有端点函数:auth.decorator
- python - 我想从一个 textarea 读取值并将相同的值传递给 django 中的另一个 textarea?
- angular - 将 SignalR 与 Angular 和 ASP.NET Core 一起使用会在发布到域后出现握手错误
- python - 如何用python发出请求?
- android - 如何在 Android 中设置背景图像并将该图像适合整个卡片以用于卡片视图?
- git - 如何在 Visual Studio Code 中将 Git hook 与 Sonar 结合使用?
- mysql - DELETE查询的SQL语句给出错误
- python-3.x - 如何遍历嵌套列表以获取其中包含唯一元素的可能结果列表?