Python 将数据帧的切片添加到新列中的另一个数据帧

Python 将数据帧的切片添加到新列中的另一个数据帧,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我有两个数据帧。一个是空的,另一个包含很多行。我想用值对数据帧进行分组,然后对每组的前3行进行切片,并将它们添加到空数据帧中。我希望每个新的3行被放入一个新的列中 我试过了,concat,join,append。。但是我不知道怎么 到目前为止,我的代码是: df = pd.Dataframe() df2 = pd.DataFrame({'C': [20, 20, 20, 20, 10, 10, 10, 30, 30, 30], 'D': [1, 2, 3,

我有两个数据帧。一个是空的,另一个包含很多行。我想用值对数据帧进行分组,然后对每组的前3行进行切片,并将它们添加到空数据帧中。我希望每个新的3行被放入一个新的列中

我试过了,concat,join,append。。但是我不知道怎么

到目前为止,我的代码是:

df = pd.Dataframe()
df2 = pd.DataFrame({'C': [20, 20, 20, 20, 10, 10, 10, 30, 30, 30],
                   'D': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})

df_dictionary = df2.groupby("C")

for key, df_values in df_dictionary:
    df_values = df_values.head(3)
    df = pd.concat(df, df_values["D"], axis=1)
    print(df)
空数据帧的结果如下所示:

index   col 1   col 2   col 3
0   1   5   8
1   2   6   9
2   3   7   10
我想将每个组的D列中的前3个值添加到空数据帧中,并每次将它们放入一个新列中


有人有什么建议吗?

这个答案有一个要求:每组必须至少有n个值

使用头部+重塑


这个答案有一个要求:每组必须至少有n个值

使用头部+重塑

我在pivot之前使用cumcount

我在pivot之前使用cumcount


我的解决方案利用groupby.groups返回的字典来构造新的数据帧

gb = df2.set_index('D').groupby('C')
pd.DataFrame.from_dict(gb.groups, orient='index').iloc[:,:3].T

Out[2033]:
   10  20  30
0   5   1   8
1   6   2   9
2   7   3  10
或者在T之后使用head


我的解决方案利用groupby.groups返回的字典来构造新的数据帧

gb = df2.set_index('D').groupby('C')
pd.DataFrame.from_dict(gb.groups, orient='index').iloc[:,:3].T

Out[2033]:
   10  20  30
0   5   1   8
1   6   2   9
2   7   3  10
或者在T之后使用head


非常感谢你。这正是我想要的:谢谢你。这正是我想要的:D
n=3 
df2.assign(key=df2.groupby('C').cumcount()).pivot(index='key',columns='C',values='D').iloc[:n,:]
Out[730]: 
C     10   20    30
key                
0    5.0  1.0   8.0
1    6.0  2.0   9.0
2    7.0  3.0  10.0
gb = df2.set_index('D').groupby('C')
pd.DataFrame.from_dict(gb.groups, orient='index').iloc[:,:3].T

Out[2033]:
   10  20  30
0   5   1   8
1   6   2   9
2   7   3  10
pd.DataFrame.from_dict(gb.groups, orient='index').T.head(3)

Out[2034]:
    10   20    30
0  5.0  1.0   8.0
1  6.0  2.0   9.0
2  7.0  3.0  10.0