python - 如何在同一个 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'
解决方案
尝试简单:
df['col_b'].apply(lambda x: ('\n'.join(x))
您的 for 循环遍历列表中的单个字符串,而不是加入整个列表。
推荐阅读
- android - ScrollView、ListView、RecyclerView 和 WebView 有什么区别?
- spring-boot - Apache Ignite:JVM 暂停时间可能过长:714 毫秒
- python - I am trying to add a PYTHONPATH to environment variable on the terminal. But several ways won't work for me
- jquery - How to Separate each Card from simultaneously flipping back together
- java - 如何在java中打印从1到100的两位数?
- ios - 来自 Amazon SNS 的 VoIP 推送
- java - JNI 对象指针
- javascript - 等待谷歌服务器端功能解决的最简单方法
- c++ - 在字符串中找到特定字符后,如何创建一个插入字符的循环?
- javascript - 类型错误:res 不是函数