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

标签 python python-3.x pandas dataframe

我有 2 个数据框。一个是空的,另一个包含很多行。我想用值对数据帧进行分组,然后将每组的前 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 个值添加到空数据框中,每次都将它们放在一个新列中。

有人有什么建议吗?

最佳答案

我在 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

关于python - 将数据帧的切片添加到新列中的另一个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55908670/

相关文章:

python - GCP dataproc with presto - 有没有办法使用 pyhive 通过 python 远程运行查询?

python - 在类内部实例化对象

Python 返回组中的第一次出现

python - 在 Pandas 系列上成对应用函数

python - 将列转换为行并在python中打印与其相邻的值和值计数

python - 将 X、Y、Z 值转换为矩阵图

python - 一组玩家的所有可能的纸牌/扑克牌组合

python - 根据组号制作新列表并添加分数

python - 无法使py2exe工作

python - 使用 Python 到 SCP 在 Windows 上使用 os、Popen 和 Paramiko 传输文件的问题