我有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个值添加到空数据帧中,并每次将它们放入一个新列中。在
有人有什么建议吗?在
这个答案有一个要求:每组必须至少有
n
个值。在使用
head
+reshape
^{pr2}$
我的解决方案利用
groupby.groups
返回的字典来构造新的数据帧或者在
^{pr2}$T
之后使用head
我在
pivot
之前使用cumcount
相关问题 更多 >
编程相关推荐