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

2024-09-29 19:24:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有2个数据帧。一个是空的,另一个包含很多行。我想用值对dataframe进行分组,然后将每组的前3行切片并将它们添加到空的dataframe中。我希望每个新的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)

结果如下所示:

^{pr2}$

我想将每个组的D列中的前3个值添加到空数据帧中,并每次将它们放入一个新列中。在

有人有什么建议吗?在


Tags: 数据代码dataframedfdictionary切片pdvalues
3条回答

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

使用head+reshape


n = 3
u = df2.groupby('C').head(n)['D'].values

pd.DataFrame(u.reshape(-1, n, order='F'), columns=[f'col {i+1}' for i in range(n)])

^{pr2}$

我的解决方案利用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

^{pr2}$

我在pivot之前使用cumcount

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

相关问题 更多 >

    热门问题