假设我有以下 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/