python-3.x - 如何使用python提取存储在csv文件中的特定键的键值
问题描述
我有一个 csv 文件,它有 3 列。其中一列具有键值形式的数据。
示例(来源、主题和视图是列)
Source Topic Views
Web {"title":"Weather for Paris
","object":"storm,hail","description":"thunderstorm"} 234
这里的主题列具有键值形式的值。这里的关键是标题、对象和描述。我只想为 csv 中的所有记录提取键“标题”下的值。
预期产出
Weather for Paris
如何使用python来完成这个?
解决方案
df = pandas.read_csv('dict.csv', usecols = ['Topic'], sep = '|')
df['Topic'].apply(lambda x: json.loads(x)['title']).values
dict.csv
结构在哪里
Source|Topic|Views
Web|{"title":"Weather for Paris","object":"storm,hail","description":"thunderstorm"}|34
请注意,我添加了分隔符|
,否则字典将无法正确解析。另一种选择是有类似的东西
Source,Topic,Views
Web,"{""title"":""Weather for Paris"",""object"":""storm,hail"",""description"":""thunderstorm""}",34
在这种情况下,您只需将sep
选项从调用中删除read_csv
推荐阅读
- r - 如何将变量和“ALL”中的唯一值添加到闪亮选择器的下拉菜单中
- excel - 打开受密码保护的工作簿仅适用于一台 PC
- vue.js - Vuex:我可以使用突变/动作的函数名称而不是常量吗?
- android - 动态更改导航返回按钮图标不起作用
- typeorm - 有没有办法选择特定的树根及其后代?
- sql - SQL:拉取前一天的活动(包括周一的周末)
- asp.net-mvc - 延长会话超时
- groovy - 在 Jenkins 管道中运行的 Groovy 脚本中解析 XML 文件的问题
- checkbox - 从导入的数据同步两个不同电子表格中的列
- ruby-on-rails - Flash 消息仅在重定向两次后显示