python - 如何更改组中的原始 DataFrame?

标签 python pandas pandas-groupby

假设我有以下 DataFrame:

import pandas as pd

df = pd.DataFrame({'label': ['a', 'a', 'b', 'b', 'a', 'b', 'c', 'c', 'a', 'a'], 
                   'numbers': [1, 1, 1, 1, 1, 2, 2, 2, 2, 2],
                   'arbitrarydata': [False] * 10})

我想根据其他两个列中的值为 arbitrarydata 列分配一个值。一个天真的方法如下:

for _, grp in df.groupby(('label', 'numbers')):
    grp.arbitrarydata = pd.np.random.rand()

自然地,这不会将更改传播回 df。有没有一种方法可以修改组以便将更改反射(reflect)在原始 DataFrame 中

最佳答案

尝试使用transform,例如:

df['arbitrarydata'] = df.groupby(('label', 'numbers')).transform(lambda x: np.random.rand())

关于python - 如何更改组中的原始 DataFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24611318/

相关文章:

python - 在 Python 中使用 __getattribute__ 或 __getattr__ 调用方法

python - 根据相似列的值在一列中填充NA值

python - 如何对 Pandas 中的多列进行分组和聚合

python - 如果日期范围介于开始日期和结束日期之间,则将类别附加到列

python - Pandas 命名聚合不适用于 resample agg

python - 制作将自己定位在列表中的按钮

python - Plotly:如何向折线图添加水平线?

python - 基本 Django 查询?

python - 检查日期列是否包含每年的所有时间

python - 浮点比较不适用于 pandas groupby 输出