python - Pandas if-else "join" 函数返回 ValueError:Series 的真值不明确
问题描述
以下是我的数据集示例:
╔═══╦════════════╦═══════════════╗
║ ║ col_1 ║ col_2 ║
╠═══╬════════════╬═══════════════╣
║ 1 ║ 106 ║ I am Alex. ║
║ 2 ║ 106 ║ I'm a student ║
║ 3 ║ 106 ║ I like apple ║
║ 4 ║ 1786 ║ Dog is a pet ║
║ 5 ║ 1786 ║ Jack is my pet║
╚═══╩════════════╩═══════════════╝
我想先将“col_1”分组,然后将“col_2”中的字符串与if-else条件相结合,即查找字符串中的最后一个字符是否以“。”结尾。
如果它以句号结尾,则使用 " ".join 加入同一组的下一个字符串(用空格连接它们)。否则,以句号加入他们。
最终结果将如下所示:
╔═══╦════════════╦══════════════════════════════════════════╗
║ ║ col_1 ║ col_2 ║
╠═══╬════════════╬══════════════════════════════════════════╣
║ 1 ║ 106 ║ I am Alex. I'm a student. I like apple ║
║ 2 ║ 1786 ║ Dog is a pet. Jack is my pet ║
╚═══╩════════════╩══════════════════════════════════════════╝
我的代码如下:
new_df = df.groupby(['col_1'])['col_2'].apply(lambda x: ' '.join(x) if x[-1:] == '.' else '. '.join(x)).reset_index()
但是我得到了这个错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
非常感谢您的帮助!
解决方案
假设您的所有字符串都没有尾随空格,为什么不直接应用'. '.join(...)
和删除加倍的结果呢?
df = pd.DataFrame({
'col1': [106,106,106,1786,1786],
'col2': ['I am Alex.','I\'m a student','I like apple','Dog is a pet','Jack is my pet']
})
result = df.groupby('col1', as_index=False).agg({'col2': lambda x: '. '.join(x)})
result['col2'] = result['col2'].str.replace('.. ', '. ', regex=False)
正如预期的那样,这让你:
col1 col2
0 106 I am Alex. I'm a student. I like apple
1 1786 Dog is a pet. Jack is my pet
推荐阅读
- sql - 如何在 SELECT 语句中分配唯一值?
- quartus - Quartus 支持内存综合吗?
- windows - AMD64 页面入口基地址字段如何将 52 位地址编码为 40 位?
- python - 如何减慢从标准输出中读取的速度
- c# - 选择自动完成中的项目时的返回值 WPF
- azure - Azure DevOps 发布管道 Powershell 脚本 MSDeploy 错误
- karma-jasmine - TypeError:创建单元测试时无法读取 null 的属性“addEventListener” - Jasmine(Angular)
- nginx - 为什么nginx要等到应用服务器终止才发送SSE?
- json - 从 JSON 字符串中获取值
- c++ - 编译包含 PETSc 库的 C++ 代码。make: 没有规则来制作目标错误信息