我有 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/