首页 > 解决方案 > 将数据帧的切片添加到新列中的另一个数据帧

问题描述

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

我已经尝试过,连接,加入,追加......但我不知道如何......

到目前为止我的代码:

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 个值添加到空数据框中,并每次将它们放入一个新列中。

有人有建议吗?

标签: pythonpython-3.xpandasdataframe

解决方案


cumcount以前用过pivot

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

推荐阅读