python - 将数据帧的切片添加到新列中的另一个数据帧
问题描述
我有 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 个值添加到空数据框中,并每次将它们放入一个新列中。
有人有建议吗?
解决方案
我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
推荐阅读
- java - split 方法如何创建 PairFunction?
- mysql - 返回 SQL 中特定行的计数
- python - 有没有办法阻止 QWindowsNativeFileDialog::OnSelectionChange(Qurl...) 退出命令行?
- sql - 如何在 WP_Query 中搜索标题、内容或元数据?
- r - 在带有 add_scatterplot 的点击事件期间,R 中的 Mapdeck 究竟返回了什么?
- html - 在调整窗口大小时调整元素大小
- python - 关于 range() 的 for 语句的问题
- javascript - nodejs https状态200但正文响应为空,ajax调用有效但返回错误状态0
- python - 为增强 Pascal Voc 数据集的原始图像添加类标签
- r - 如何根据函数参数重命名 R 中的对象?