首页 > 解决方案 > 如何使用python提取存储在csv文件中的特定键的键值

问题描述

我有一个 csv 文件,它有 3 列。其中一列具有键值形式的数据。

示例(来源、主题和视图是列)

Source        Topic                                                       Views

Web        {"title":"Weather for Paris 
            ","object":"storm,hail","description":"thunderstorm"}          234

这里的主题列具有键值形式的值。这里的关键是标题、对象和描述。我只想为 csv 中的所有记录提取键“标题”下的值。

预期产出

Weather for Paris

如何使用python来完成这个?

标签: python-3.xcsvkey-value

解决方案


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


推荐阅读