首页 > 解决方案 > 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().

非常感谢您的帮助!

标签: pythonpandasif-statementpandas-groupby

解决方案


假设您的所有字符串都没有尾随空格,为什么不直接应用'. '.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

推荐阅读