Pandas通过

时间:2018-02-22 19:55:49

标签: python pandas pandas-groupby

我喜欢

   a   flag
0  1  False
1  0  False
2  1  False
3  0  False
4  0  False

并且假设我想在列True中的每个组上随机添加一些a以获取

   a   flag
0  1   True
1  0   True
2  1   True
3  0  False
4  0   True

到目前为止,我可以使用以下代码

执行此操作
import pandas as pd
import numpy as np

def rndm_flag(ds, n):
    l = len(ds)
    n = min([l, n])
    vec = ds.sample(n).index
    ds["flag"] = np.where(ds.index.isin(vec),
                         True, ds["flag"])
    return(ds)

N = 5
df = pd.DataFrame({"a":np.random.randint(0,2,N),
                   "flag":[False]*N})

dfs = list(df.groupby("a"))
dfs = [x[1] for x in dfs]
df = pd.concat([rndm_flag(x, 2) for x in dfs])
df.sort_index(inplace=True)

但我想知道是否有另一种(更优雅)的方式。

1 个答案:

答案 0 :(得分:0)

这应该会给你一些想法:

## create dataframe
df = pd.DataFrame({'a':[1,0,1,0,0], 'b':False})

## create flag
d['b'] = d.groupby('a').transform(lambda x: (np.random.choice([True, False], len(x), p = [0.65,0.35])))
print(d)

   a      b
0  1  False
1  0   True
2  1  False
3  0   True
4  0   True