pandas -将字符串转换为字符串列表 [英] pandas - convert string into list of strings
本文介绍了 pandas -将字符串转换为字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个'file.csv'文件可以和熊猫一起阅读:
I have this 'file.csv' file to read with pandas:
Title|Tags
T1|"[Tag1,Tag2]"
T1|"[Tag1,Tag2,Tag3]"
T2|"[Tag3,Tag1]"
使用
df = pd.read_csv('file.csv', sep='|')
输出为:
Title Tags
0 T1 [Tag1,Tag2]
1 T1 [Tag1,Tag2,Tag3]
2 T2 [Tag3,Tag1]
我知道列Tags
是完整字符串,因为:
I know that the column Tags
is a full string, since:
In [64]: df['Tags'][0][0]
Out[64]: '['
我需要将其阅读为像["Tag1","Tag2"]
这样的字符串列表.我尝试了此问题中提供的解决方案但是那里没有运气,因为我有[
和]
字符,它们实际上使事情弄乱了.
I need to read it as a list of strings like ["Tag1","Tag2"]
. I tried the solution provided in this question but no luck there, since I have the [
and ]
characters that actually mess up the things.
预期输出应为:
In [64]: df['Tags'][0][0]
Out[64]: 'Tag1'
推荐答案
您可以手动拆分字符串:
You can split the string manually:
>>> df['Tags'] = df.Tags.apply(lambda x: x[1:-1].split(','))
>>> df.Tags[0]
['Tag1', 'Tag2']
这篇关于 pandas -将字符串转换为字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文