Python 分组和样本熊猫

Python 分组和样本熊猫,python,pandas,random,pandas-groupby,Python,Pandas,Random,Pandas Groupby,在对多个列执行groupby之后,我尝试对结果数据进行采样。如果相应的groupby有2个以上的元素,我想获取样本2条记录,否则获取所有记录 df: 目标测向: col1 col2 col3 col4 A1 A2 A3 A4 or A5 or A6 A1 A2 A3 A4 or A5 or A6 B1 B2 B3 B4 B1 B2 B3 B5 C1 C2 C3 C4

在对多个列执行groupby之后,我尝试对结果数据进行采样。如果相应的groupby有2个以上的元素,我想获取样本2条记录,否则获取所有记录

df:

目标测向:

col1   col2   col3   col4
A1     A2     A3     A4 or A5 or A6
A1     A2     A3     A4 or A5 or A6
B1     B2     B3     B4
B1     B2     B3     B5
C1     C2     C3     C4
我提到A4、A5或A6是因为,当我们取样时,三者中的任何一个都可能返回

这就是我迄今为止所尝试的:

trial = pd.DataFrame(df.groupby(['col1', 'col2','col3'])['col4'].apply(lambda x: x if (len(x) <=2) else x.sample(2)))

trial=pd.DataFrame(df.groupby(['col1','col2','col3'])['col4'].apply(lambda x:x if(len(x)默认情况下无需将其转换为pandas数据帧

trial=df.groupby(['col1', 'col2','col3'])['col4'].apply(lambda x: x if (len(x) <=2) else x.sample(2))
我认为需要双-第一个用于删除
3.rd
级别的
MultiIndex
,第二个用于将
MultiIndex
转换为列:

trial= (df.groupby(['col1', 'col2','col3'])['col4']
        .apply(lambda x: x if (len(x) <=2) else x.sample(2))
        .reset_index(level=3, drop=True)
        .reset_index())

我得到这个错误:TypeError:无法在序列上重置_索引以创建数据帧谢谢,我可以在我提供的示例数据帧上运行这个,但是当我在另一个数据帧的切片上运行相同的时,它只给我数字索引。我尝试重置父数据帧的索引,但我仍然得到sameData是一样的?什么返回
print(df.info)
?对不起,我忘记了
()
-
print(df.info())
RangeIndex:10个条目,0到9个数据列(共5列):索引10个非空int64列10个非空对象列2个非空对象列3个非空对象列4个非空对象数据类型:int64(1),object(4) 内存使用:560.0+字节无
trial.reset_index(inplace=True,drop=False)
trial= (df.groupby(['col1', 'col2','col3'])['col4']
        .apply(lambda x: x if (len(x) <=2) else x.sample(2))
        .reset_index(level=3, drop=True)
        .reset_index())
trial= (df.groupby(['col1', 'col2','col3'])['col4']
        .apply(lambda x: x if (len(x) <=2) else x.sample(2))
        .reset_index()
        .drop('level_3', 1))

print (trial)
  col1 col2 col3 col4
0   A1   A2   A3   A4
1   A1   A2   A3   A6
2   B1   B2   B3   B4
3   B1   B2   B3   B5
4   C1   C2   C3   C4