python - 数据框转换和字符串连接
问题描述
我有一个看起来像这样的熊猫数据框:
index, a, b
0, i, this
1, belong, is
2, here, right
0, only, one
0, two, another
1, items, example
我正在尝试获取输出,以便将运行索引折叠起来并连接字符串:
index, a, b
0, i belong here, this is right
1, only, one
2, two items, another example
知道如何以干净的方式做到这一点吗?
解决方案
0
您需要创建以inindex
和累积总和开头的组,然后聚合join
:
#if index is column
df = df.groupby(df['index'].eq(0).cumsum(), as_index=False).agg(' '.join)
#if index is not column
#df = df.groupby((df.index == 0).cumsum(), as_index=False).agg(' '.join)
print (df)
a b
0 i belong here this is right
1 only one
2 two items another example
详情:
print (df['index'].eq(0).cumsum())
0 1
1 1
2 1
3 2
4 3
5 3
Name: index, dtype: int32
#print ((df.index == 0).cumsum())
#[1 1 1 2 3 3]
推荐阅读
- ruby-on-rails - RESTful 嵌套控制器命名最佳实践
- python - 矩阵乘以转置向量
- docker - 如何在 docker compose 中为每个容器创建单独的卷
- android - 如何确定手机视口的有效像素数
- r - 如何根据数据类型在两列之间交换数据?[R]
- python - 如何使用 Python 中的 REST API 遍历 Confluence Cloud 中 Space 中的所有页面
- assembly - 在 lw 指令之后带有 beq 的 MIPS 流水线?
- java - 防止应用程序自动注销
- passwords - 无效的密码重置令牌
- python - 优化以从列表中获取最多和最少出现的对