python - 将列表列转换为 Pandas 中的字符串

标签 python pandas

我有一个名为 df 的 df,就像这样。 tag_position 是字符串或列表。但我希望它们都是字符串。我怎样才能做到这一点?我还想删除末尾的空白区域。

输入

id  tag_positions
1   center
2   right
3   ['left']
4   ['center ']
5   [' left']
6   ['right']
7   left

预期输出

id  tag_positions
1   center
2   right
3   left
4   center
5   left
6   right
7   left

最佳答案

你可以爆炸然后剥离:

df.tag_positions = df.tag_positions.explode().str.strip()

得到

   id tag_positions
0   1        center
1   2         right
2   3          left
3   4        center
4   5          left
5   6         right
6   7          left

关于python - 将列表列转换为 Pandas 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67285804/

相关文章:

python - 如何选择pandas中每个唯一记录的第一行和最后一行

python - Django 验证错误消息仅显示在管理页面中

python - 在 CVXOPT 中制定某个 LP

python - 如何使用lxml获取url

python - 以同样的方式转换 CSV 文件的文件夹,然后使用 python 输出多个数据帧

python - 错误 : Unsupported format, 或损坏的文件:预期的 BOF 记录;发现 b'<## NASC'

python - tkinter 按钮无法打开不同的 python 代码

python - 如何加快从oracle sql到pandas df的数据加载速度

python - 从 MySQL 获取表到 Pandas 的最快方法

python - 如何以有效的方式将具有 MultiIndex 的数据帧合并到另一个数据帧中?