[英]python dict in comma separated csv file
Python dict的格式如下:
'{"a":1, "b":2, "c":3}'
注意,它使用逗号分隔不同的key:value对。
问题是我有一个CSV文件,该文件也是用逗号分隔的各列:
'
"id", "gender", "age", "name"
"001", "male", "14", "{"first":"Mike", "last":"Green"}"
"002", "female", "15", "{"first":"Kate", "last":"Spear"}"
'
当我做
pandas.read_csv('csvfile.csv', sep = ',', names=["id", "gender", "age", "name"])
我有:
'
"id", "gender", "age", "name"
"001", "male", "14", "{"first":"Mike"
"002", "female", "15", "{"first":"Kate"
'
我猜的原因是csv阅读器将dict中的逗号作为csv文件中的分隔符。 由于我仅指定了4个列,分别为“ id”,“ gender”,“ age”,“ name””,因此它忽略了姓氏。
有什么想法或可能的解决方案吗? 谢谢!
您可以更改read_csv
使用的定界符。 如果可以更改csv文件以使用分号分隔列,则可以使用read_csv(file.csv, sep=';'...)
或者,您可以修复来自
"001", "male", "14", "{"first":"Mike", "last":"Green"}"
至
"001", "male", "14", "{'first':'Mike', 'last':'Green'}"
当然,这两种方法都意味着编辑csv文件。
第二个听起来更好。 正则表达式(\\{[^"]*)(")([^}]*\\})
可用于匹配括号内的引号。 (未试)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.