首页 > 解决方案 > 如何在同一个 Pandas 数据框单元格中的列表元素之间放置换行符?

问题描述

我有一个带有一列字符串列表的熊猫数据框。如何使列表元素在同一行(和同一单元格)内的 Pandas 中逐行显示?

给定这样的数据框:

+-------+-----------------------------------+
| col_a |               col_b               |
+-------+-----------------------------------+
| A     | ['string1', 'string2', 'string3'] |
| B     | ['string4', 'string5', 'string6'] |
+-------+-----------------------------------+

我想让它像这样显示:

+-------+---------+
| col_a |  col_b  |
+-------+---------+
| A     | string1 |
|       | string2 |
|       | string3 |
| B     | string4 |
|       | string5 |
|       | string6 |
+-------+---------+

注意我想将它们保留在同一个单元格中,只需在元素之间添加换行符,如果可能的话,可以选择删除方括号和引号。

我试过这个:

df['col_b'].apply(lambda x: ('\n'.join(i) for i in x), axis=1)

但它越来越TypeError: <lambda>() got an unexpected keyword argument 'axis'

标签: pythonpandas

解决方案


尝试简单:

df['col_b'].apply(lambda x: ('\n'.join(x))

您的 for 循环遍历列表中的单个字符串,而不是加入整个列表。


推荐阅读